How do I convert a Color to a Brush in XAML?

Viewed 59267

I want to convert a System.Windows.Media.Color value to a System.Windows.Media.Brush. The color value is databound to a Rectangle object's Fill property. The Fill property takes a Brush object, so I need an IValueConverter object to perform the conversion.

Is there a built-in converter in WPF or do I need to create my own? How do I go about creating my own if it becomes necessary?

8 Answers

Using Pattern matching there's no need for neither null checking and double casting:

public class ColorToSolidBrushValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is Color color) return new SolidColorBrush(color);

        throw new InvalidOperationException(nameof(color));
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => new NotImplementedException();
}

Optional implementation for ConvertBack:

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value is SolidColorBrush brush)
    {
        return brush.Color;
    }

    throw new InvalidOperationException(nameof(brush));
}
Related