MultiBinding 与 Binding 一样继承自 BindingBase,因此可以使用 Binding 的地方都可以使用 MultiBinding。
namespace System.Windows.Data
{
[ContentProperty("Bindings")]
public class MultiBinding : BindingBase, IAddChild
{
...
public Collection<BindingBase> Bindings { get; }
}
}
例子:
在一个注册界面中,当两次输入的密码一致且邮箱不为空时,可以点击提交。
<StackPanel Grid.Row="12">
<TextBox x:Name="passwd"/>
<TextBox x:Name="passwdConfirm"/>
<TextBox x:Name="email"/>
<Button x:Name="buttonSubmit" Content="click me" Width="100" HorizontalAlignment="Left" Click="buttonSubmit_Click"/>
</StackPanel>
public class LogonMultiBindingConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if ( !values.Cast<string>().Any(text => string.IsNullOrWhiteSpace(text))
&& values[0].ToString() == values[1].ToString()
&& !string.IsNullOrWhiteSpace(values[2].ToString()))
{
return true;
}
return false;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Binding b1 = new Binding("Text") { Source = this.passwd };
Binding b2 = new Binding("Text") { Source = this.passwdConfirm };
Binding b3 = new Binding("Text") { Source = this.email };
MultiBinding mb = new MultiBinding() { Mode=BindingMode.OneWay };
mb.Bindings.Add(b1);
mb.Bindings.Add(b2);
mb.Bindings.Add(b3);
mb.Converter = new LogonMultiBindingConverter();
this.buttonSubmit.SetBinding(Button.IsEnabledProperty, mb);