Monday, November 17, 2014

Converters - String To Brush Converter

Note: This is not my original work. Have blogged it here just for my future reference and of course if someone wants to use it.

This converter is used to associate a String to a brush color. It was really helpful as we needed to get the color detail from database depending on certain values and apply that color at run time.

 Basic class

public class StringToBrushConverter : IValueConverter
    {
        public StringToBrushConverter()
        {
           
        }

        public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            switch (value.ToString())
            {
                case "Gray":
                    return Brushes.Gray;
                case "Red":
                    return Brushes.IndianRed;
                case "Green":
                    return Brushes.LightGreen;
                default:
                    return Brushes.White;
            }
        }

        public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }


Usage

public StringToBrushConverter StringToBrushConverter { get; set; }
StringToBrushConverter = new StringToBrushConverter();
 var colorBinding = new Binding(visaType + ColorName) { Converter = StringToBrushConverter };
if ( condition1 )
{
stackPanel.SetBinding(StackPanel.BackgroundProperty, colorBinding);
}

No comments:

Post a Comment