问题
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