将静态资源传递给自定义System.Windows.Data.IValueConverter?

时间:2012-05-02 08:10:23

标签: wpf xaml ivalueconverter

考虑下面的值转换器。我可以轻松地将诸如“Red”和“Green”之类的值传递给我的转换器,但是如何传递在XAML中定义的画笔?

如何将FalseBrush绑定到MyNiceBrush

<local:MyBrushConverter x:Key="BackgroundConverter" FalseBrush="Red" TrueBrush="Green" />

<LinearGradientBrush x:Key="MyNiceBrush" StartPoint="0,0" EndPoint="0,1">
    <GradientStop Offset="0" Color="#4C7F00" />
    <GradientStop Offset="1" Color="#A0B529" />
</LinearGradientBrush>

在XAML中,我将对象的属性绑定到此转换器:Background="{Binding MyClass.TrueOrFalseProperty, Converter={StaticResource BackgroundConverter} ...

这是我的转换器:

public class MyBrushConverter : IValueConverter
{
    public Brush FalseBrush { get; set; }
    public Brush TrueBrush { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((bool)value)
            return TrueBrush;
        else
            return FalseBrush;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

1 个答案:

答案 0 :(得分:1)

<local:MyBrushConverter x:Key="BackgroundConverter" FalseBrush={StaticResource MyNiceBrush} TrueBrush="Green" />