wpf how to use a converter for child bindings of m

2019-05-10 01:18发布

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>

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
}

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?

1条回答
欢心
2楼-- · 2019-05-10 01:58

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;
}
查看更多
登录 后发表回答