WPF如何为Multibinding的子绑定使用转换器?

3
我需要一个多绑定的布尔属性集合,但是需要对其中一些进行反转,就像这个例子一样:
<StackPanel>
    <StackPanel.IsEnabled>
        <MultiBinding Converter="{StaticResource BooleanAndConverter}">
            <Binding Path="IsInitialized"/>
            <Binding Path="IsFailed" Converter="{StaticResource InverseBooleanConverter}"/>
        </MultiBinding>
    </StackPanel.IsEnabled>
</StackPanel.IsEnabled>

但我从一个名为 InverseBooleanConverter 的程序中得到了一个 InvalidOperationException 错误,错误信息是“目标必须是布尔值”。我的 InverseBooleanConverter 代码如下:

[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是:

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.");
    }
}

那么,如何在子绑定中使用转换器呢?

你知道你自己正在抛出异常吗?不要检查“targetType”。检查“value”是否为布尔值,然后返回其相反值。 - Clemens
1个回答

2

无需检查targetType,只需检查传入Convert方法的value的类型即可。

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接