有时候,UI需要的信息不止一个数据来源,这时候就需要使用多路绑定MultiBinding,上一节中我们实现了通过一个TextBox是否为空来控制一个Button的可用性。下面我们实现通过两个TextBox来控制Button的可用性:两个TextBox的不为空且内容一致时,Button才可用;否则不可用。
运行效果如下,在两个TextBox内容不一致时,Button不可用:
首先,搭建界面,Xmal代码如下:
<Window x:Class="_6_38.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="192,191,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="169,75,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="169,122,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
然后,创建一个Convert,此时需要继承自IMultiValueConverter,而不是之前的IValueConverter。
public class MultiBindingConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if(values.Cast<string>().Any(text=>string.IsNullOrEmpty(text))==false
&& values[0].ToString() == values[1].ToString())
{
return true;
}
return false;
}
public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//准Á?备À?基¨´础ä?binding
Binding b1 = new Binding("Text") { Source = this.textBox1 };
Binding b2 = new Binding("Text") { Source = this.textBox2 };
//准Á?备À?多¨¤路¡¤binding
MultiBinding mb = new MultiBinding() { Mode=BindingMode.OneWay };
mb.Bindings.Add(b1);
mb.Bindings.Add(b2);
MultiBindingConverter mbc=new MultiBindingConverter();
mb.Converter = mbc;
//设¦¨¨置?关?联¢a
this.button1.SetBinding(Button.IsEnabledProperty, mb);
}
}
运行效果如下,在两个TextBox内容不一致时,Button不可用:
在两个TextBox内容一致时,Button可用: