wpf如何使用转换器进行多绑定的子绑定?

时间:2014-11-22 18:09:32

标签: c# wpf xaml converter multibinding

我需要一组束布尔属性的多重绑定,但是反过来其中一些就像一个例子:

<StackPanel>
    <StackPanel.IsEnabled>
        <MultiBinding Converter="{StaticResource BooleanAndConverter}">
            <Binding Path="IsInitialized"/>
            <Binding Path="IsFailed" Converter="{StaticResource InverseBooleanConverter}"/>
        </MultiBinding>
    </StackPanel.IsEnabled>
</StackPanel.IsEnabled>

但我从InvalidOperationException得到一个InverseBooleanConverter,并带有消息“目标必须是布尔值”。我的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.");
    }
}

那么,如何使用具有子绑定的转换器?

1 个答案:

答案 0 :(得分:1)

无需检查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;
}