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

前端 未结 7 1890
逝去的感伤
逝去的感伤 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:19

    In addition to HCLs answer: If you don't want to care if System.Windows.Media.Color is used or System.Drawing.Color you can use this converter, which accepts both:

    public class ColorToSolidColorBrushValueConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            switch (value)
            {
                case null:
                    return null;
                case System.Windows.Media.Color color:
                    return new SolidColorBrush(color);
                case System.Drawing.Color sdColor:
                    return new SolidColorBrush(System.Windows.Media.Color.FromArgb(sdColor.A, sdColor.R, sdColor.G, sdColor.B));
            }
    
            Type type = value.GetType();
            throw new InvalidOperationException("Unsupported type [" + type.Name + "]");
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    } 
    
    0 讨论(0)
提交回复
热议问题