WPF中的binding(十二)- 多路Binding

        有时候,UI需要的信息不止一个数据来源,这时候就需要使用多路绑定MultiBinding,上一节中我们实现了通过一个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可用:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值