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

前端 未结 7 1888
逝去的感伤
逝去的感伤 2020-11-27 05:52

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

7条回答
  •  有刺的猬
    2020-11-27 06:05

    It seems that you have to create your own converter. Here a simple example to start:

    public class ColorToSolidColorBrushValueConverter : IValueConverter {
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            if (null == value) {
                return null;
            }
            // For a more sophisticated converter, check also the targetType and react accordingly..
            if (value is Color) {
                Color color = (Color)value;
                return new SolidColorBrush(color);
            }
            // You can support here more source types if you wish
            // For the example I throw an exception
    
            Type type = value.GetType();
            throw new InvalidOperationException("Unsupported type ["+type.Name+"]");            
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            // If necessary, here you can convert back. Check if which brush it is (if its one),
            // get its Color-value and return it.
    
            throw new NotImplementedException();
        }
    }
    

    To use it, declare it in the resource-section.

    
    

    And the use it in the binding as a static resource:

    Fill="{Binding Path=xyz,Converter={StaticResource ColorToSolidColorBrush_ValueConverter}}"
    

    I have not tested it. Make a comment if its not working.

提交回复
热议问题