public class RGBConverter : IMultiValueConverter
{
//正向修改,整合颜色值
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if(values==null || values.Length<1)
{
return null;
}

byte r = System.Convert.ToByte(values[0]);
byte g = System.Convert.ToByte(values[1]);
byte b = System.Convert.ToByte(values[2]);

Color col = Color.FromRgb(r, g, b);
SolidColorBrush brush = new SolidColorBrush(col);
return brush;
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}

<Window.Resources>
<local:RGBConverter x:Key="rgbConverter"/>
<Style TargetType="Slider">
<Setter Property="BorderBrush" Value="Silver"/>
<Setter Property="BorderThickness" Value="3"/>
</Style>
</Window.Resources>
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Red: " HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Label Grid.Row="1" Grid.Column="0" Content="Green:" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<Label Grid.Row="2" Grid.Column="0" Content="Blue:" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding ElementName=slider_R,Path=Value}" VerticalAlignment="Bottom"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding ElementName=slider_G,Path=Value}" VerticalAlignment="Bottom" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding ElementName=slider_B,Path=Value}" VerticalAlignment="Bottom"/>
<Slider x:Name="slider_R" Minimum="0" Maximum="255" IsSnapToTickEnabled="True" Grid.Row="0" Grid.Column="2" HorizontalAlignment="Stretch" />
<Slider x:Name="slider_G" Minimum="0" Maximum="255" IsSnapToTickEnabled="True" Grid.Row="1" Grid.Column="2" HorizontalAlignment="Stretch" />
<Slider x:Name="slider_B" Minimum="0" Maximum="255" IsSnapToTickEnabled="True" Grid.Row="2" Grid.Column="2" HorizontalAlignment="Stretch"/>
<Rectangle Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3" Stroke="Black">
<Rectangle.Fill>
<MultiBinding Converter="{StaticResource ResourceKey=rgbConverter}">
<Binding ElementName="slider_R" Path="Value"/>
<Binding ElementName="slider_G" Path="Value"/>
<Binding ElementName="slider_B" Path="Value"/>
</MultiBinding>
</Rectangle.Fill>
</Rectangle>
</Grid>

WPF MultiBinding,多值转化器IMultiValueConverter,自制调色板 palette-LMLPHP

05-26 15:31