#222 – Example: Changing a Color Using RGB Sliders

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);
            }
        }

Advertisement

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

One Response to #222 – Example: Changing a Color Using RGB Sliders

  1. yggddrtg says:

    nyc work

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: