WPF Binding to change fill color of ellipse

后端 未结 3 1259
臣服心动
臣服心动 2021-02-13 12:44

How do I programmatically change the color of an ellipse that is defined in XAML based on a variable?

Everything I\'ve read on binding is based on collections and lists

3条回答
  •  抹茶落季
    2021-02-13 13:14

    what you will need to do is implement a custom converter to convert the colour to the brush object. Something like this...

    public class ColorToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            System.Drawing.Color col = (System.Drawing.Color)value;
            Color c = Color.FromArgb(col.A, col.R, col.G, col.B);
            return new System.Windows.Media.SolidColorBrush(c);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            SolidColorBrush c = (SolidColorBrush)value;
            System.Drawing.Color col = System.Drawing.Color.FromArgb(c.Color.A, c.Color.R, c.Color.G, c.Color.B);
            return col;
        }
    }
    

    And then specify that converter in your binding

    Fill="{Binding Colors.Red, Converter={StaticResource ColorToBrushConverter }"
    

提交回复
热议问题