#1,138 – Value Converter Example for Output

The Convert method of a value converter is used to convert from a binding source (e.g. a property) to a binding target (e.g. the attribute of a control).  Below is a simple example, showing how we can convert from an integer to a brush of a particular color.

In XAML, we have a Slider that ranges from 0-255 and binds to a property, storing the integer value that the user selects.  We then bind to the same property for a rectangle shape’s Fill property.  The Fill property wants a Brush object, so we use a value converter to convert from the integer to a brush.

<Window x:Class="WpfApplication1.MainWindow"
        Title="Value Converter" SizeToContent="WidthAndHeight">

        <local:IntToBlueBrushValueConverter x:Key="intToBlueBrushValueConverter"/>

    <StackPanel Margin="15">
        <Slider Minimum="0" Maximum="255"
                Value="{Binding BlueValue}"/>
        <Label Content="{Binding BlueValue}"/>
        <Rectangle Height="80" Width="80"
            Fill="{Binding Path=BlueValue, Converter={StaticResource intToBlueBrushValueConverter}}"/>

The code-behind is straightforward.

    public partial class MainWindow : Window, INotifyPropertyChanged
        public MainWindow()
            this.DataContext = this;

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        protected virtual void OnPropertyChanged(string prop)
            PropertyChanged(this, new PropertyChangedEventArgs(prop));

        private int blueValue;
        public int BlueValue
            get { return blueValue; }
                if (blueValue != value)
                    blueValue = value;

In the value converter, we create a solid color brush whose R and G values are 0 and whose B value is derived from the integer (slider position).

    public class IntToBlueBrushValueConverter : IValueConverter
        // Convert from int to System.Windows.Media.Brush
        // where brush is color with R=0, G=0 and B=int
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

            int blueVal = (int)value;
            blueVal = Math.Min(Math.Max(0, blueVal), 255);

            return new SolidColorBrush(Color.FromRgb(0, 0, (byte)blueVal));

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

At run-time, the color of the rectangle changes as we move the slider.





About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,138 – Value Converter Example for Output

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: