#222 – Example: Changing a Color Using RGB Sliders
February 19, 2011 Leave a comment
Here’s an example of changing a color at run-time, using three sliders.
The XAML defines a control and three sliders:
<Window.Resources>
<SolidColorBrush x:Key="magicBrush" Color="Red"/>
</Window.Resources>
<StackPanel>
<Ellipse Height="100" Width="200" Fill="{StaticResource magicBrush}" Margin="30"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Label Content="Red" VerticalAlignment="Center"/>
<Slider Name="sliR" Width="150" Margin="10" Minimum="0" Maximum="255" TickFrequency="1" IsSnapToTickEnabled="True"
Value="255"
ValueChanged="sli_ValueChanged"/>
<Label Content="{Binding ElementName=sliR, Path=Value}" VerticalAlignment="Center"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Label Content="Green" VerticalAlignment="Center"/>
<Slider Name="sliG" Width="150" Margin="10" Minimum="0" Maximum="255" TickFrequency="1" IsSnapToTickEnabled="True"
ValueChanged="sli_ValueChanged"/>
<Label Content="{Binding ElementName=sliG, Path=Value}" VerticalAlignment="Center"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Label Content="Blue" VerticalAlignment="Center"/>
<Slider Name="sliB" Width="150" Margin="10" Minimum="0" Maximum="255" TickFrequency="1" IsSnapToTickEnabled="True"
ValueChanged="sli_ValueChanged"/>
<Label Content="{Binding ElementName=sliB, Path=Value}" VerticalAlignment="Center"/>
</StackPanel>
</StackPanel>
In code, we have a single method that executes when the sliders change, which changes the brush color:
private void sli_ValueChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
{
SolidColorBrush magicBrush = (SolidColorBrush)this.Resources["magicBrush"];
if ((sliR != null) && (sliG != null) && (sliB != null))
{
magicBrush.Color = Color.FromRgb((byte)sliR.Value, (byte)sliG.Value, (byte)sliB.Value);
}
}

