WPF 如何将转换器用于多重绑定的子绑定

本文关键字:绑定 用于 转换器 WPF | 更新日期: 2023-09-27 18:31:44

我需要一堆布尔属性的多重绑定,但要反转其中一些,例如:

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

但是我从InverseBooleanConverter那里得到了一条InvalidOperationException,上面有消息"目标必须是布尔值"。我的反向布尔转换器是:

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

布尔值和转换器是:

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

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

WPF 如何将转换器用于多重绑定的子绑定

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