Analysing a colorchooser in WPF, I came to the point not only binding to a single element property but also to multiple properties. The color of a rectangle should change according current values of 4 sliders. Suppose the sliders are named with "slAlpha", "slRed", "slGreen", "slBlue".
Resulting screenshot:
A multiple binding in XAML is then declared in the following way:
<Rectangle Name="rtColor" Margin="25">
<Rectangle.Fill>
<SolidColorBrush>
<SolidColorBrush.Color>
<MultiBinding Converter="{StaticResource convertColor}">
<MultiBinding.Bindings>
<Binding ElementName="slAlpha" Path="Value" />
<Binding ElementName="slRed" Path="Value" />
<Binding ElementName="slGreen" Path="Value" />
<Binding ElementName="slBlue" Path="Value" />
</MultiBinding.Bindings>
</MultiBinding>
</SolidColorBrush.Color>
</SolidColorBrush>
</Rectangle.Fill>
</Rectangle>
But now how do we transfer the 4 slider values to one single brush color? Note the "Converter" property. It maps to a static resource named "convertColor" declared within the window container:
<Window.Resources>
<local:ConvertColor x:Key="convertColor" />
<ImageBrush x:Key="newtelligencelogo" TileMode="Tile" Viewport="0,0,240,51" ViewportUnits="Absolute" ImageSource= "newtelligencelogo.bmp"/>
</Window.Resources>
It serves as link between XAML and some conversion functionality in code. So what is still missing is a class implementing the IMultiValueConverter interface doing the color mixing. It must be named as the type specified in the resource tag:
public class ConvertColor : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
float alpha = (float)(double)(values[0]);
float red = (float)(double)(values[1]);
float green = (float)(double)(values[2]);
float blue = (float)(double)(values[3]);
return Color.FromScRgb(alpha, red, green, blue);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException("Not supported");
}
}
For the Visual Studio 2005 solution click here.