wpf how to use a converter for child bindings of multibinding?

删除回忆录丶 提交于 2019-12-22 11:01:42

问题


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:


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


来源:https://stackoverflow.com/questions/27080733/wpf-how-to-use-a-converter-for-child-bindings-of-multibinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!