« Spam Bots ... | Main | Setup WPF/E without installing extra VS addins »

ColorToBrushConverter

Although it took me 2 minutes to create this morning after searching for 2 minutes -- I thought I'd post this:

(I needed a Color to SolidColorBrush converter so that I could display the actual physical color rather than the name)

public class ColorToBrushConverter : IValueConverter
{
#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Color)
{
return new SolidColorBrush((Color)value);
}
return null;
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}

#endregion
}

Although very simple, it was very useful in this situation:

I have an object with a property of type Color:

public Color Color
{
get { return _color; }
set { _color = value; RaisePropertyChanged("Color"); }
}

I wanted to bind a rectangle with the color rather than just the name of the color:

<Rectangle Fill="{Binding Color, Converter={StaticResource myColorToBrushConverter}}" Width="20" Height="20" />

I created an instance of the converter in the local resources:

<ListView.Resources>
<local:ColorToBrushConverter x:Key="myColorToBrushConverter" />
</ListView.Resources>

And made sure I added the clr namespace to the XAML file:

xmlns:local="clr-namespace:WPFCheckBoxDemo"

And here it is in a simple list:

More on the list and why I was doing this in a later post ...

Help support my web site by searching and buying through Amazon.com (in assocation with Amazon.com).