簡體   English   中英

wpf如何使用轉換器進行多綁定的子綁定?

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

我需要一個束綁定布爾屬性的多綁定,但反過來其中一些像一個例子:

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

那么,如何使用具有子綁定的轉換器?

無需檢查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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM