Wednesday, June 7, 2017

WPF Tip #12 - Extended WPF Toolkit - ColorCanvas

Last time in Tip #11, I explained the Extended WPF Toolkit and the different versions that are available. In the quick-n-dirty example, I added a SplitButton with a ColorCanvas that displays when opening the dropdown portion of the buttom.

In this tip, we are going to add just a few lines of code to take the color selected in the ColorCanvas and apply it as the background color of the SplitButton.

Let's start with the Xaml. There are two changes needed here (highlighted below). The first is to name the button so it can be referenced from the application's code. The second is adding a handler to the ColorCanvas' SelectedColorChanged event. This event fires every time the color changes on the canvas and provides the OldValue and NewValue as parameters in the event.

<tk:SplitButton x:Name="mainSplitButton" Content="Pick a Color" Height="32" Width="120">
         <tk:ColorCanvas SelectedColorChanged="ColorCanvas_OnSelectedColorChanged" />

In the code behind for the Window, I have added the ColorCanvas_OnSelectedColorChanged event handler with some code to set the SplitButton's background color to a new SolidColorBrush the color of the NewValue selected on the ColorCanvas, provided it's not null.

private void ColorCanvas_OnSelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color?> e)
     if (e.NewValue.HasValue)
         mainSplitButton.Background = new SolidColorBrush(e.NewValue.Value);

You could add an else condition to handle nulls by setting the background color back to some default color. Here's what the end result looks like.


If you were following the MVVM pattern in your application, you would handle this through data binding and commands. In Tip #13, we will add MVVMLight to the mix and rework the example to follow this pattern. Tags: ,,

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.