2014-11-22 65 views
2

我需要的一堆布尔属性,但与反演有些像一个例子的multibinding:wpf如何使用转换器进行多重绑定的子绑定?

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

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

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

+0

你知道你自己在抛出异常吗?不要检查'targetType'。检查“value”是否为bool,而不是返回。 – Clemens 2014-11-22 18:15:15

回答

0

有没有必要检查targetType,只需检查传入Convert方法的value的类型。

​​