I have a custom class, \"FavoriteColor\" that has three properties, R, G and B. Now I want to draw a rectangle and fill it
Let's do this using a MultiBinding and an IMultiValueConverter. Here's a full sample.
First, the xaml for Window1. We'll set up three Sliders and bind their values to the Window's Background property via a SolidColorBrush.
Next, the converter. Note that I'm not doing any error checking here - you really should check that the length of the values array is 3 and that the individual values are valid bytes etc.
public class RgbConverter : IMultiValueConverter
{
#region IMultiValueConverter Members
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var r = System.Convert.ToByte(values[0]);
var g = System.Convert.ToByte(values[1]);
var b = System.Convert.ToByte(values[2]);
return Color.FromRgb(r, g, b);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
That's it! No other code-behind is necessary.