WPF如何使用转换器进行多重绑定的子绑定? [英] wpf how to use a converter for child bindings of multibinding?
本文介绍了WPF如何使用转换器进行多重绑定的子绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要对布尔型布尔属性进行多重绑定,但需要像例子中那样反转其中一些:
I need a multibinding of bunch boolean properties but with inversing some of these like an example:
<StackPanel>
<StackPanel.IsEnabled>
<MultiBinding Converter="{StaticResource BooleanAndConverter}">
<Binding Path="IsInitialized"/>
<Binding Path="IsFailed" Converter="{StaticResource InverseBooleanConverter}"/>
</MultiBinding>
</StackPanel.IsEnabled>
</StackPanel.IsEnabled>
但是我从 InverseBooleanConverter
并显示消息目标必须为布尔值。我的InverseBooleanConverter是:
But I got a InvalidOperationException
from a InverseBooleanConverter
with message "The target must be a boolean". My InverseBooleanConverter is:
[ValueConversion(typeof(bool), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if (targetType != typeof(bool))
throw new InvalidOperationException("The target must be a boolean");
return !(bool)value;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
和BooleanAndConverter为:
and BooleanAndConverter is:
public class BooleanAndConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return values.All(value => (!(value is bool)) || (bool) value);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("BooleanAndConverter is a OneWay converter.");
}
}
那么,如何使用带有子绑定的转换器?
So, how to use a converters with child bindings?
推荐答案
无需检查 targetType
,只需检查 value
的类型传递给Convert方法。
There is no need to check the targetType
, just check the type of value
passed into Convert method.
public object Convert(object value, Type targetType,
object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is bool))
throw new InvalidOperationException("Value is not bool");
return !(bool)value;
}
这篇关于WPF如何使用转换器进行多重绑定的子绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文