0

Consider the value converter below. I can easily pass values such as "Red" and "Green" to my converter, but how could I pass a brush defined in XAML?

How do I bind FalseBrush to 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>

In XAML, I bind my object's property to this converter: Background="{Binding MyClass.TrueOrFalseProperty, Converter={StaticResource BackgroundConverter} ...

Here's my converter:

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();
    }
}
l33t
  • 18,692
  • 16
  • 103
  • 180
  • Why can't you do this via `StaticResource`? `FalseBrush={StaticResource MyNiceBrush}`. – Zabavsky May 02 '12 at 08:18
  • I've tried that, but I keep getting an exception: "Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception." – l33t May 02 '12 at 08:22
  • Lol... if I put my brush resource above the converter declaration it works! – l33t May 02 '12 at 08:23

1 Answers1

1
<local:MyBrushConverter x:Key="BackgroundConverter" FalseBrush={StaticResource MyNiceBrush} TrueBrush="Green" />
Zabavsky
  • 13,340
  • 8
  • 54
  • 79