WPF之Binding基础十一 MultiBinding多路绑定

  当在Ui上显示的东西由多个数据源决定的时候就需要多路绑定

XAML代码

<Window x:Class="MultiBinding多路绑定.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">
<StackPanel Background="LightBlue">
<TextBox x:Name="txtbox1" Height="23" Margin="5"/>
<TextBox x:Name="txtbox2" Height="23" Margin="5"/>
<TextBox x:Name="txtbox3" Height="23" Margin="5"/>
<TextBox x:Name="txtbox4" Height="23" Margin="5"/>
<Button x:Name="button1" Content="注册" Width="80" Margin="5"/>
</StackPanel>
</Window>

CS代码

namespace MultiBinding多路绑定
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

Binding bind1 = new Binding("Text") { Source = this.txtbox1 };
Binding bind2 = new Binding("Text") { Source = this.txtbox2 };
Binding bind3 = new Binding("Text") { Source = this.txtbox3 };
Binding bind4 = new Binding("Text") { Source = this.txtbox4 };

MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay };
mb.Bindings.Add(bind1);
mb.Bindings.Add(bind2);
mb.Bindings.Add(bind3);
mb.Bindings.Add(bind4);

mb.Converter = new LogonMultiBindingConverter();
this.button1.SetBinding(Button.IsEnabledProperty, mb);
}

}
}

LogonMultiBindingConverter类

namespace MultiBinding多路绑定
{
public class LogonMultiBindingConverter:System.Windows.Data.IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (!values.Cast<string>().Any(text => string.IsNullOrEmpty(text))
&& values[0].ToString() == values[1].ToString()
&& values[2].ToString() == values[3].ToString())
{
return true;
}

return false;

}
public object[] ConvertBack(object values, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

原文地址:https://www.cnblogs.com/lijin/p/3151101.html