【WPF】wpf用MultiBinding解决Converter需要动态传参的问题,以Button为例

原文: 【WPF】wpf用MultiBinding解决Converter需要动态传参的问题,以Button为例

      用Binding并通过Converter转换的时候,可能偶尔会遇到传参的问题,一般通过设置xaml中的BindingParameter属性来给Converter传递参数。

      但是这个BindingParameter只支持已经定义好的资源类型(Resource),不支持int,Object等类型,在BindingParameter中也无法再次通过Binding的方法动态赋值。所以,折腾来折腾去还不如用MultiBinding得了。


1.XAML中的使用。

                        <Button  Margin="20,0"  Style="{StaticResource btnRecomendStyle}" >
                            <Button.Content>
                                <MultiBinding Converter="{StaticResource bool_PercentToStringConverter}">
                                    <Binding Path="IsTest"></Binding>
                                    <Binding Path="TestPercent"></Binding>
                                </MultiBinding>
                            </Button.Content>
                            <Button.Command>
                                <MultiBinding Converter="{StaticResource bool_PercentToCommandConverter}">
                                    <Binding Path="IsTest"></Binding>
                                    <Binding Path="TestPercent"></Binding>
                                </MultiBinding>
                            </Button.Command>
                        </Button>
Button的Content和Command都进行了两个绑定,这两个绑定将作为下面Converter类Object[]中的两个参数。

2.定义MultiConverter类,bool_PercentToStringConverter:

 class Bool_PercentToStringConverter : IMultiValueConverter
    {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            bool b;
            int Percent;
            Boolean.TryParse(values[0].ToString(), out b);
            Int32.TryParse(values[1].ToString(), out Percent);
            if (b)
            {
                if (Percent < 100)
                {
                    return Application.Current.FindResource("IDS_CANCEL");
                }
                else
                {
                    return Application.Current.FindResource("IDS_DONE");
                }
            }
            else
            {
                return Application.Current.FindResource("IDS_TEST");
            }
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        
    }
这里不再实现IValueConverter接口,而是实现IMultiValueConverter。Object[] values里保存的就是传入的两个Binding。


猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/9091895.html