深入浅出WPF之MultiBinding--笔记(2015.03.10)

    当UI需要显示的信息由不止一个数据来源决定,此时需要使用MultiBinding,即多路Binding。MultiBinding与Binding都以BindingBase为基类,也就是说,凡是能使用Binding对象的场合都能使用MultiBinding。MultiBinding具有一个名为Bindings的属性,其类型是Collection<BindingBase>,通过这个属性MultiBinding把一组Binding对象聚合起来,处在该集合中的Binding对象都可以拥有自己的数据校验和转换机制,它们汇聚起来的数据共同决定传往MultiBinding目标的数据。

    注意:

    (1)、MultiBinding对于添加子级Binding的顺序敏感,因为这个顺序决定了汇集到Converter里数据的顺序;

    (2)、MultiBinding的Converter实现的时IMultiValueConverter接口。

XAML代码:

     <StackPanel Background="LightBlue">
        <TextBox x:Name="textBox1" Height="23" Margin="5"/>
        <TextBox x:Name="textBox2" Height="23" Margin="5, 0"/>
        <TextBox x:Name="textBox3" Height="23" Margin="5"/>
        <TextBox x:Name="textBox4" Height="23" Margin="5, 0"/>
        <Button x:Name="button1" Content="Submit" Width="80" Margin="5"/>
    </StackPanel>

C#代码:

 public class LogonMultiBindingConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.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, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.SetMultiBinding();
        }

        private void SetMultiBinding()
        {
            Binding binding1 = new Binding("Text") { Source = this.textBox1 };
            Binding binding2 = new Binding("Text") { Source = this.textBox2 };
            Binding binding3 = new Binding("Text") { Source = this.textBox3 };
            Binding binding4 = new Binding("Text") { Source = this.textBox4 };

            MultiBinding mb = new MultiBinding() { Mode = BindingMode.OneWay };
            mb.Bindings.Add(binding1);
            mb.Bindings.Add(binding2);
            mb.Bindings.Add(binding3);
            mb.Bindings.Add(binding4);
            mb.Converter = new LogonMultiBindingConverter();

            this.button1.SetBinding(Button.IsEnabledProperty, mb);
        }
    }

你可能感兴趣的:(WPF,MultiBinding)