WPF Tips for Microsoft Visual Studio and .NET developers. Take your XAML skills up a notch.
Saturday, November 30, 2019
.NET Core Book Review on Morning Dew
I just published a book review on my Morning Dew blog that may be of interest to my readers here. C# 8.0 and .NET Core 3.0 - Modern Cross-Platform Development is a new title by Mark Price from Packt Publishing. While it covers a broad range of .NET Core topics, there are chapters on both Xamarin and Windows Desktop application development.
Go check it out here!
Friday, December 21, 2018
WPF Tip #21 - Create a Reusable ToolTip With a Header and Icon
In this tip, we're going to create a custom control derived from ToolTip to create a headered tooltip with an icon. Creating it as a custom control makes it trivial to add the tooltip to any control in your project.
This simple example will include a specific icon and has a property to hide/show the icon. I'll explain later how you could update the control's implementation to accept an icon through binding, enabling different icons across different uses.
The first step is to create the custom control class that inherits from ToolTip. Here is the implementation for HeaderedToolTip.
[TemplatePart(Name = PART_TooltipHeader, Type = typeof(TextBlock))]
[TemplatePart(Name = PART_TooltipIcon, Type = typeof(ContentControl))]
[TemplatePart(Name = PART_TooltipContents, Type = typeof(TextBlock))]
public class HeaderedToolTip : ToolTip
{
private const string PART_TooltipHeader = "PART_TooltipHeader";
private const string PART_TooltipIcon = "PART_TooltipIcon";
private const string PART_TooltipContents = "PART_TooltipContents";
private TextBlock _headerBlock = null;
private ContentControl _iconControl = null;
private TextBlock _contentsBlock = null;
static HeaderedToolTip()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(HeaderedToolTip), new FrameworkPropertyMetadata(typeof(HeaderedToolTip)));
}
public string HeaderText
{
get => (string)GetValue(HeaderTextProperty);
set => SetValue(HeaderTextProperty, value);
}
// Using a DependencyProperty as the backing store for HeaderText. This enables animation, styling, binding, etc.
public static readonly DependencyProperty HeaderTextProperty =
DependencyProperty.Register("HeaderText", typeof(string), typeof(HeaderedToolTip), new UIPropertyMetadata(string.Empty));
public string ContentText
{
get => (string)GetValue(ContentTextProperty);
set => SetValue(ContentTextProperty, value);
}
// Using a DependencyProperty as the backing store for HeaderText. This enables animation, styling, binding, etc.
public static readonly DependencyProperty ContentTextProperty =
DependencyProperty.Register("ContentText", typeof(string), typeof(HeaderedToolTip), new UIPropertyMetadata(string.Empty));
public Visibility IconVisibility
{
get => (Visibility)GetValue(IconVisibilityProperty);
set => SetValue(IconVisibilityProperty, value);
}
// Using a DependencyProperty as the backing store for IconVisibility. This enables animation, styling, binding, etc.
public static readonly DependencyProperty IconVisibilityProperty =
DependencyProperty.Register("IconVisibility", typeof(Visibility), typeof(HeaderedToolTip), new UIPropertyMetadata(Visibility.Collapsed));
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_headerBlock = GetTemplateChild(PART_TooltipHeader) as TextBlock;
_iconControl = GetTemplateChild(PART_TooltipIcon) as ContentControl;
_contentsBlock = GetTemplateChild(PART_TooltipContents) as TextBlock;
}
}
Some of this code is not necessary for our tooltip, but I added it here to illustrate how you can get a reference to parts of your custom control within the class in OnApplyTemplate(). This would be useful if you need to respond to any events fired from the controls that make up your custom controls. You would add the event handler hooks here after resolving them through GetTemplateChild.
The next step is to set up the template in a ResourceDictionary. Here is the XAML markup from my ToolTipResourceDictionary.xaml file.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ToolTipSample.Controls">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="..\Images\vector_Information.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type local:HeaderedToolTip}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:HeaderedToolTip}">
<Border BorderThickness="2" BorderBrush="Black">
<Grid Background="Ivory">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{TemplateBinding HeaderText}"
x:Name="PART_TooltipHeader"
FontWeight="Bold"
VerticalAlignment="Bottom"
Margin="4"
HorizontalAlignment="Left"/>
<ContentControl Grid.Column="1"
HorizontalAlignment="Right"
VerticalAlignment="Top"
x:Name="PART_TooltipIcon"
Content="{StaticResource vector_Information}"
Visibility="{TemplateBinding IconVisibility}"
Height="16" Width="16"
Margin="4"/>
<TextBlock Grid.Row="1"
Grid.ColumnSpan="2"
Margin="4,12,4,6"
x:Name="PART_TooltipContents"
Text="{TemplateBinding ContentText}"
TextWrapping="Wrap"
MaxWidth="200"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
The final step is to consume our custom tooltip in a control somewhere in our project. I have create a Window containing a horizontally aligned StackPanel with two Grids. Each grid contains a border that glows a different color when you mouse over it, one blue, one gold. The second grid is disabled to demonstrate the ToolTipService.ShowOnDisabled attached property. Each Grid.ToolTip contains an instance of our HeaderedToolTip custom tooltip control.
<Window.Resources>
<ResourceDictionary Source="..\ToolTipResourceDictionary.xaml"/>
</Window.Resources>
<StackPanel Orientation="Horizontal">
<Grid ToolTipService.ShowOnDisabled="True">
<Border Width="180" Height="180"
Margin="10" Background="Transparent"
BorderBrush="White" BorderThickness="2" Opacity="1.0">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect ShadowDepth="0" Color="Gold" Opacity="1" BlurRadius="20"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="4"/>
</Border>
<Grid.ToolTip>
<local:HeaderedToolTip HeaderText="My first fantastic header."
ContentText="Some tooltip text. This could get really long."
IconVisibility="Visible"/>
</Grid.ToolTip>
</Grid>
<Grid IsEnabled="False" ToolTipService.ShowOnDisabled="True">
<Border Width="180" Height="180"
Margin="10" Background="Transparent"
BorderBrush="White" BorderThickness="2" Opacity="1.0">
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Effect">
<Setter.Value>
<DropShadowEffect ShadowDepth="0" Color="Blue" Opacity="1" BlurRadius="20"/>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="4"/>
</Border>
<Grid.ToolTip>
<local:HeaderedToolTip HeaderText="My second fantastic header."
ContentText="Some tooltip text. This could get really, really long."
IconVisibility="Collapsed"/>
</Grid.ToolTip>
</Grid>
</StackPanel>
That's it. Here's a look at the tooltip in action. Please excuse my vector paragraph image in place of an actual Info icon.
Of course, in your actual implementation, data like the header's tooltip and contents will be driven from ViewModel data binding.
If you want to allow a custom icon for each use of the HeaderedToolTip, you would add an Image as another DependencyProperty on the custom control class and as another TemplatePart in the ResourceDictionary.
That's all for this WPF Tip. You can take any of these concepts and apply them to other custom controls you may need in your own applications. For more information about creating controls, check out Microsoft Docs.
Happy coding!
Thursday, August 9, 2018
Can I Port My Windows Desktop Application to .NET Core? Find Out and Prepare Today!
Did you know that soon you will be able to build and run your WPF (and UWP & WinForms) applications against .NET Core?
Desktop Packs
At the Microsoft Build conference in May, it was announced that the .NET team was working on some Windows-only "Desktop Packs" that could be installed on top of .NET Core v3.0. These packs would include:
- WPF
- WinForms
- UWP
- Entity Framework v6
This will bring the benefits of .NET Core to desktop client applications running on Windows. In my opinion, the biggest benefits of porting your desktop app to .NET Core will be significant performance gains and full access to Windows 10 APIs.
Obviously, in most cases, it won't be as simple as changing a project property and rebuilding your app. Project files will need to be upgraded to .NET Core format, and some legacy APIs will not be available, even in the Desktop Pack packages. This week, it has become more clear exactly which APIs will not be available in .NET Core 3.0 with Desktop Packs.
Portability Analyzer
On Wednesday, the .NET team released a Portability Analyzer tool to scan your .NET desktop applications and determine how ready they are to upgrade to .NET Core 3.0. The tool will scan your .NET binaries and dependencies and produce an Excel report (PortabilityReport.xlsx) with several tabs:
Portability Summary - This sheet contains a list of the assemblies scanned, their current .NET version target, and the % compatibility they are expected to have with .NET Core 3.0.
Details - This sheet provides details on exactly which target type and member are currently used by one of your assemblies that is not compatible with .NET Core 3.0. There is a column for Recommended Changes, but none of my incompatibilities had any recommendations.
Missing assemblies - If your assemblies reference any other assemblies which could not be resolved by the tool, they will be listed here.
My Thoughts
I ran the tool on a large application with a mix of WinForms and WPF windows. The folder contains over 900 DLLs. My thoughts:
First, I was pleasantly surprised at how fast the tool ran its analysis. It completed scanning this large application in less than a minute. I was expecting to go get a cup of coffee and a snack while it ran.
Second, the team has really included a lot of desktop APIs in these packs. I was not expecting so many of my DLLs to report at 100% compatible.
Third, many of the incompatible APIs are somewhat expected. Here are a few that came back in the report here:
- Microsoft.VisualBasic.* - If you have VB apps, and use APIs in this namespace, expect a lot of lines to appear in your report.
- System.Drawing.Design.* and System.Drawing.ImageConverter - Much of the System.Drawing namespaces was ported to .NET Core, but not everything. If you're doing anything advanced or uncommon, you'll probably find some issues here.
- Things that are less common in modern development like System.Xml.XmlDataDocument, System.Runtime.Remoting.Messaging, and System.Activator.GetObject.
Console Tool
If you would prefer to run the analyzer against several applications and product individual reports for each, you can use a console analyzer with a batch file or PowerShell script instead. That version is available here, and instructions for using it are in the .NET team's post about the Portability Analyzer.
Wrap-Up
Go get your app ready for .NET Core 3.0 today! Your users will thank you later.
Thursday, November 30, 2017
WPF Tip #20 - Extended WPF Toolkit - IconButton Control
IconButton derives from a WPF Button and adds the ability to optionally place an Image to the left or right of your button's Content. There are a handful of properties available on top of the existing Button properties - Icon and IconBackground plus properties to change the button's appearance when users mouse over or press the button:
- MouseOverBackground
- MouseOverForeground
- MouseOverBorderBrush
- MousePressedBackground
- MousePressedForeground
- MousePressedBorderBrush
<xctk:IconButton Content="Launch Me" Padding="4" HorizontalAlignment="Center" VerticalAlignment="Center" IconLocation="Right"> <xctk:IconButton.Icon> <Image Source="/WpfApp1;component/Images/Launchpad_Icon.png" Width="16" Margin="4,0,0,0"/> </xctk:IconButton.Icon> </xctk:IconButton>
The result is a window with a single "Launch Me" IconButton. There's an Apple-style launch icon to the right of the text set in the Content property. The image I used is a .png file in my project's Images folder set as a Resource. If you wanted to deploy the actual .png file, you would update the file to be "Content" and set the Image's Source property to "Images/Launchpad_Icon.png". This is the same practice you would use for any WPF image source.
All of these properties can be set up via MVVM, data binding and code in your ViewModels to load the image and set its location at runtime based on other application configuration or user preferences.
Here's is a look at the window at runtime:
It's a simple control that can save you a little bit of control templating. If this is something you could use in your project, the toolkit is free and available on NuGet.
Happy coding!
Thursday, September 7, 2017
WPF Tip #19 - Extended WPF Toolkit - Zoom in with the Magnifier Control
In the Xaml below, I have added a Magnifier to the top-level grid in my Window.
<Grid> <tk:MagnifierManager.Magnifier> <tk:Magnifier BorderBrush="MediumPurple" BorderThickness="2" Radius="80" ZoomFactor=".4" /> </tk:MagnifierManager.Magnifier> <tk:CheckListBox ItemsSource="{Binding Sentences, IsAsync=True}" SelectedItem="{Binding SelectedSentence}" Command="{Binding ItemSelectedCommand}"/>
The CheckedListBox from Tip #18 is still in place, displaying results from my Bacon Ipsum generator from Tip #17. Running the application, we see my random list items with a zoom region that follows my mouse as I move it around the Window.
Pretty simple! Go check it out for yourself. You can easily add a bound visibility property to hide/show the control from a toolbar or other button in your app.
Happy coding!
Monday, August 14, 2017
WPF Tip #18 - Extended WPF Toolkit - Using the CheckedListBox Control
This control provides all of the functionality expected from a ListBox with the addition of checkboxes as a visual cue to indicate the selection state of each item.
Using the control is quite simple. Here's an example of the XAML required to display a CheckedListBox on a WPF window. It is binding to the same collection of Sentence objects used in Tip #17.
<tk:CheckListBox ItemsSource="{Binding Sentences, IsAsync=True}" SelectedItem="{Binding SelectedSentence}" Command="{Binding ItemSelectedCommand}"/>
ItemsSource binding to a collection to populate the list items. SelectedItem provides a way to find out the currently 'selected' item, the last item checked/unchecked. The Command will fire each time an item in the list is checked or unchecked, allowing ViewModel logic to act on this change.
Go give it a try in your WPF project. Happy coding!
Wednesday, August 2, 2017
WPF Tip #17 - Extended WPF Toolkit - BusyIndicator Control
Here is a fun little example that wraps a WPF DataGrid in a BusyIndicator. This is the entirety of the XAML inside the root Grid on the application's main window.
<tk:BusyIndicator IsBusy="{Binding IsGridLoading}" BusyContent="Loading, please wait..." DisplayAfter="0"> <DataGrid local:Commands.DataGridDoubleClickCommand="{Binding GridDoubleClickCommand}" ItemsSource="{Binding Sentences, IsAsync=True}"/> </tk:BusyIndicator>
The DataGridDoubleClickCommand is a work-around to make the DataGrid's MouseDoubleClick event work with ICommand in when data binding in MVVM. More info here.
In the MainViewModel, there is an IsGridLoading boolean property that will be used to toggle the BusyIndicator on/off. The GridDoubleClickCommand invokes OnGridDoubleClicked() when the user double-clicks somewhere on the DataGrid at runtime. In this method, we're clearing and repopulating the Sentences ObservableCollection to which our DataGrid is bound. Notice the use of async/await. This is necessary to make the BusyIndicator appear. Without this, the UI will freeze during the update and never show the BusyIndicator control.
private async void OnGridDoubleClicked() { //set the IsBusy before you start the thread IsGridLoading = true; RaisePropertyChanged(nameof(IsGridLoading)); //no direct interaction with the UI is allowed from this method lock (_sentenceLock) { Sentences.Clear(); } await BuildSentenceList(5, 15, 25, 50); //work has completed. you can now interact with the UI IsGridLoading = false; RaisePropertyChanged(nameof(IsGridLoading)); }
The _sentenceLock allows us to update our ObservableCollection on a background thread. You must also initialize the collection with this code in your constructor. This tells WPF to update the collection on the UI thread and which lock object to use. More info here.
BindingOperations.EnableCollectionSynchronization(Sentences, _sentenceLock);
Each row in the DataGrid will be populated with some random Bacon Ipsum data in the BuildSentenceList method. There is an API if you would like to remove the hard-coded array of words.
private async Task BuildSentenceList(int minWords, int maxWords, int minSentences, int maxSentences) { var words = new[]{"bacon", "ipsum", "dolor", "tail", "amet", "swine", "chicken", "short", "loin", "jowl", "turkey", "ball", "tip", "beef", "shank", "rump", "t-bone", "ham", "porchetta", "filet", "pork", "jerky", "hock", "meatball", "biltong", "steak", "brisket"}; var rand = new Random(); int numSentences = rand.Next(maxSentences - minSentences) + minSentences + 1; int numWords = rand.Next(maxWords - minWords) + minWords + 1; var result = new StringBuilder(); Task t = Task.Run(() => { for (int s = 0; s < numSentences; s++) { for (int w = 0; w < numWords; w++) { if (w > 0) { result.Append(" "); } result.Append(words[rand.Next(words.Length)]); } result.Append(". "); lock (_sentenceLock) Sentences.Add(new Sentence() {SentenceContent = result.ToString()}); Thread.Sleep(100); result.Clear(); } }); await t; }
When the code to populate the grid fires, thanks to the 100ms Thread.Sleep between each row generated, you can see the grid slowly populating with data behind the busy indicator.
It's a great control. Just remember to update your data on a background thread!
Happy coding!
Tuesday, July 25, 2017
WPF Tip #16 - Extended WPF Toolkit - ChildWindow & MessageBox Controls
The ChildWindow control is a handy alternative to opening a separate dialog from the current application window, collecting a few pieces of data. The MessageBox operates similarly, but only presents some information and allows the user to respond, like any typical WinForm or WPF MessageBox.
In an MVVM world, opening another dialog typically either involves another View/ViewModel combination or a service to open a simple message/input dialog and return the result to the current View/ViewModel. This control is best used to replace a simple MessageBox service or when another View/ViewModel are being considered, but logically the data collected is limited and still belongs in the current ViewModel.
The use of the controls consists of a WindowContainer element containing one or more ChildWIndow and MessageBox elements. In this sample, the Window's main grid contains a WindowContainer with two ChildWindow elements and one MessageBox. They all begin with a Closed WindowState, and are opened with a button click. Here is a snippet of the view's XAML:
<StackPanel Grid.Row="2" Orientation="Horizontal" VerticalAlignment="Top"> <Button Content="Toggle Window 1" Height="40" Width="120" Margin="2" Command="{Binding ButtonOneCommand}"/> <Button Content="Toggle Window 2" Height="40" Width="120" Margin="2" Command="{Binding ButtonTwoCommand}"/> <Button Content="Toggle Window 3" Height="40" Width="120" Margin="2" Click="ButtonBase_OnClick"/> </StackPanel> <tk:WindowContainer Grid.Row="2"> <tk:ChildWindow WindowBackground="Blue" Left="75" Top="50" Width="275" Height="125" WindowState="{Binding WindowOneState}"> <TextBlock Text="This is a child window" Padding="10"/> </tk:ChildWindow> <tk:ChildWindow WindowBackground="Green" Left="175" Top="125" Width="275" Height="125" WindowState="{Binding WindowTwoState}"> <StackPanel> <TextBlock Text="This is a child window with a checkbox." Padding="10"/> <CheckBox Content="Check me!" Margin="8"/> </StackPanel> </tk:ChildWindow> <tk:MessageBox Caption="Toolkit Message" x:Name="SampleMsgBox" Text="You have an alert!"/> </tk:WindowContainer>
The MessageBox's button has a Click event handler to display the control:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { SampleMsgBox.ShowMessageBox(); }
The two ChildWindows are opened with Commands attached to the first two buttons in our Window's ViewModel:
private void OnButtonOneClicked() { if (WindowOneState == WindowState.Open) WindowOneState = WindowState.Closed; else WindowOneState = WindowState.Open; RaisePropertyChanged(nameof(WindowOneState)); } public RelayCommand ButtonOneCommand { get; private set; } private void OnButtonTwoClicked() { if (WindowTwoState == WindowState.Open) WindowTwoState = WindowState.Closed; else WindowTwoState = WindowState.Open; RaisePropertyChanged(nameof(WindowTwoState)); } public RelayCommand ButtonTwoCommand { get; private set; }
The ChildWindows can be closed again by using the close button on the element or by clicking it's Open button again. This second option is not available when the ChildWindow has IsModal set to true. You'll notice the WindowState property of the two ChildWindows is bound to the ViewModel. This two-way binding ensures the IF statements in the command methods will work properly regardless of how each window is closed.
Here is a look at the Window with the second ChildWindow open. This control contains a TextBlock and a CheckBox inside a StackPanel. The ChildWindow can contain only one direct child, like a Window or UserControl.
There are tons or other uses for these controls and many properties I haven't touched on at all. Go explore them for yourself and download the toolkit today.
Happy coding!
Tuesday, July 18, 2017
WPF Tips Update - The Extended WPF Toolkit Has a New Home
Hello WPF fans! You may have noticed that I am a fan of Xceed's free Extended WPF Toolkit. I am actually a huge fan of free tools and productivity gains in general.
This week when I started working on WPF Tip #16, I was pleased to notice that Xceed has released v3.1 of the Extended WPF Toolkit and moved the source code from CodePlex to GitHub! The move to GitHub was, of course, motivated by Microsoft announcement that CodePlex is shutting down in the coming months.
Download, Star and Watch the Extended WPF Toolkit on GitHub
The changelog for v3.1.0 includes 37 fixes and enhancements. The Plus Edition snagged an additional 19 fixes and improvements including a Windows 10 theme, but Plus received v3.1.0 last year. It pays to pay, it seems.
Learn all about the toolkit on GitHub or check out WPF Tip #11. This tip was my introductory post about the controls. And be sure to stay tuned for more WPF Tips about these controls and lots more!
Happy coding!
Friday, June 23, 2017
WPF Tip #14 - Extended WPF Toolkit - The CalculatorUpDown Control
The CalculatorUpDown control is a hybrid of sorts. It takes the functionality of an up/down numeric control and adds a dropdown button. Clicking on the dropdown button pops open a Calculator control. The output of the calculator displays in its window as well as in the text portion of the CalculatorUpDown.
Let's take a simple example of the control's use and walk through a few of the properties and how they impact the control's functionality. Here is the XAML:
<tk:CalculatorUpDown Grid.Row="1" Height="32" VerticalAlignment="Top" FormatString="C2" Watermark="Calculate!" Increment=".01" Maximum="9999.99" Minimum="0.01"/>Upon first launching the window, this is how the control looks:
There is a numeric up/down with a watermark reading "Calculate!" and a dropdown button to open the calculator control. Let's click the up button to start.
The Increment property is set to ".01" and the FormatString is "C2", so our value has incremented to $0.01 or 1 U.S. cent. You'll notice that the down button is now disabled because the Minimum property is currently equal to the control's Value.
Now to explore the calculator control a little. Click the dropdown button and enter a calculation.
As you use the calculator, you will notice that the calculator window updates as you enter and calculate values, but the textbox of the control only updates to show results of calculations. If the calculated value falls outside the Maximum or Minimum properties, it will default to those Max/Min values.
There was no code required on our part to add this rich functionality or our application, only the XAML markup seen above. You certainly could take this a step further by adding some data binding and leveraging other properties that the control exposes to do things like allowing the user to change the number format.
Happy coding!
Tuesday, June 13, 2017
WPF Tip #13 - Extended WPF Toolkit - ColorCanvas with MVVMLight, Binding and EventToCommand
In Tip #12, we used a ColorCanvas control in a SplitButton to change the Background color of the SplitButton using an event in the code behind. In this tip, we will do the same thing with data binding and commands using MVVMLight.
The first step is to add the MVVMLight NuGet package to the project:
Adding the package will add and update several classes in the project. We now have a MainViewModel and ViewModelLocator inside a ViewModel folder. The locator class exposes each ViewModel in the project so they can be bound in your views. To make the locator discoverable to the views in the project, MVVMLight added a new resource to the App.xaml:
<Application.Resources>
<ResourceDictionary>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" xmlns:vm="clr-namespace:WpfApp1.ViewModel" />
</ResourceDictionary>
</Application.Resources>
Now lets start with the changes we have to make. First remove the event handler from the MainWindow.xaml.cs. The next step is to replace that functionality with some decoupled logic in the MainViewModel. Two things are needed:
- A ButtonBrush property to bind the SplitButton's Background property.
- A ChangeBrushColorCommand RelayCommand to bind to the ColorChanged event of the ColorCanvas.
An OnColorChanged method is added to do the work needed when the RelayCommand is invoked. These are hooked up in the constructor, along with some default colors for the SplitButton. I made the button different colors at design-time and runtime as a way to validate that my binding code isn't broken. Here's the complete MainViewModel implementation:
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
if (IsInDesignMode)
{
ButtonBrush = new SolidColorBrush(Colors.LightGray);
}
else
{
ButtonBrush = new SolidColorBrush(Colors.LightSkyBlue);ChangeBrushColorCommand = new RelayCommand<Color?>(OnColorChanged);
}
}public SolidColorBrush ButtonBrush { get; set; }
internal void OnColorChanged(Color? p_Param)
{
if (p_Param.HasValue)
{
ButtonBrush = new SolidColorBrush(p_Param.Value);
}
else
{
ButtonBrush = new SolidColorBrush(Colors.Transparent);
}RaisePropertyChanged(nameof(ButtonBrush));
}public RelayCommand<Color?> ChangeBrushColorCommand { get; private set; }
}
The next thing we need is a converter class to convert the event args of the ColorChanged event to the Color? parameter type of our RelayCommand. SelectedColorChangedToColorConverter implements the IEventArgsConverter in MvvmLight. It's similar to value converters you may have created for data binding in WPF (see WPF Tip #4).
public class SelectedColorChangedToColorConverter : IEventArgsConverter
{
public object Convert(object value, object parameter)
{
var args = (RoutedPropertyChangedEventArgs<Color?>)value;return args.NewValue ?? Colors.Transparent;
}
}
Finally, lets make a few changes to the MainWindow view.
Set the DataContext for the Window using the ViewModelLocator:
DataContext="{Binding Main, Source={StaticResource Locator}}"
Add the converter to the Window.Resources:
<Window.Resources>
<ResourceDictionary>
<local:SelectedColorChangedToColorConverter x:Key="SelectedColorChangedToColorConverter" />
</ResourceDictionary>
</Window.Resources>
Update the SplitButton to bind its Background property and the ColorCanvas to use the MVVMLight EventToCommand trigger, hooking up our RelayCommand through the converter.
<tk:SplitButton Content="Pick a Color" Height="32" Width="120" Background="{Binding ButtonBrush}">
<tk:SplitButton.DropDownContent>
<tk:ColorCanvas x:Name="MainColorCanvas">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedColorChanged">
<command:EventToCommand Command="{Binding ChangeBrushColorCommand, Mode=OneWay}"
EventArgsConverter="{StaticResource SelectedColorChangedToColorConverter}"
PassEventArgsToCommand="True"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</tk:ColorCanvas>
</tk:SplitButton.DropDownContent>
</tk:SplitButton>
That's it!. Same functionality, but now with better separation between view and code.
Happy coding! (P.S. - I hope to get some proper code formatting hooked up to Blogger soon… or maybe a new blogging platform. Thanks for bearing with me.)
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:SplitButton.DropDownContent>
<tk:ColorCanvas SelectedColorChanged="ColorCanvas_OnSelectedColorChanged" />
</tk:SplitButton.DropDownContent>
</tk:SplitButton>
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.
Thursday, June 1, 2017
WPF Tip #11 - Free Controls with the Extended WPF Toolkit Community Edition
Currently available on Codeplex, the Community Edition of the toolkit includes nearly 50 WPF controls. These are just a few:
- CheckListBox
- ColorPicker
- DataGrid
- DateTimePicker
- DropDownButton
- MaskedTextBox
- RichTextBox
- WatermarkTextBox
- Wizard
The latest release of the community edition is 3.0.0 and was released in Dec. 2016. I have recently contacted Xceed to inquire about their plans for the future of the toolkit and whether it will be migrated to GitHub or another host. As you may be aware, Codeplex is shutting down this year. See Brian Harry's post about the transition to GitHub for Codeplex projects.
EDIT: A representative replied to me to inform me that there will be an announcement about the migration of the Extended WPF Toolkit from Codeplex within a month.
In the spirit of including some code in these tips, here is a quick sample of the little bit of code required to add a SplitButton that opens a ColorPicker control for the user:
<Window x:Class="WpfApp1.MainWindow"The end result when running the app looks like this with the button open:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
xmlns:tk="http://schemas.xceed.com/wpf/xaml/toolkit"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<tk:SplitButton Content="Pick a Color" Height="32" Width="120">
<tk:SplitButton.DropDownContent>
<tk:ColorCanvas />
</tk:SplitButton.DropDownContent>
</tk:SplitButton>
</Grid>
</Window>
The color picker itself require a little more code to setup. Let's take a look at its use in our next tip.
Happy coding!
Tuesday, May 16, 2017
WPF Tip #10 - Update ObservableCollection From a Background Thread
Pete Brown has a detailed blog post about updating ObservableCollection from background threads. I wanted to share the link to his post from 2012 and share a quick code snippet that illustrates how to do this in .NET 4.5 and later.
Before .NET 4.5, background updates to an ObservableCollection had to dispatch calls to the UI thread. Now all that is required is making a single call after initializing the collection in your ViewModel or other .NET class:
public ObservableCollection<MyObservableType> MyObservableCollection { get; set; }
private object _myCollectionLock = new object();
public MainViewModel()
{
MyObservableCollection = new ObservableCollection<MyObservableType>();
BindingOperations.EnableCollectionSynchronization(MyObservableCollection, _myCollectionLock);
}
Go check out Pete's post with the full details.
Cheers!
Wednesday, April 26, 2017
WPF Tip #9 - ObservableCollection and the CollectionChanged Event
Tip #9 will examine something that seems like it should work according to the documentation on MSDN, but I have seen it not work as expected.
When using ObservableCollection<T>, if some code in your application needs to react when items are added or removed from the collection the CollectionChanged event can be handled.
private ObservableCollection<Pill> _pills = new ObservableCollection<Pill>();
public MainWindow()
{
InitializeComponent();
Pills.CollectionChanged += Pills_CollectionChanged;
}public ObservableCollection<Pill> Pills
{
get { return _pills; }
set { _pills = value; }
}void Pills_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// Pills Collection Changed - do something
}
The issue I have encountered with this code is that setting that value of the Pills property directly does not always fire the CollectionChanged event.
Pills = someOtherPillCollection;
What I did to work around this was to remove the property setter and only work with the collection through its properties. In this case, by using Clear() and Concat<T>().
Pills.Clear();
Pills.Concat<Pill>(someOtherPillCollection);
ObservableCollection does not have an AddRange() method. You could write your own extension method to do it, but I prefer to use the LINQ extension method Concat<T>().
Has anyone else seen this same issue?
Thursday, April 6, 2017
WPF Tip #8 - Grids and Rendering Performance
Today's tip is a quick one. It's about choosing the best panel for the layout of the UIElements in your WPF Window or Control.
Many developers will default to putting everything into a Grid. It's easy. They're flexible and offer many layout options. When a Window is relatively simple and performance is not being analyzed by users or stakeholders, using Grids everywhere might be ok. However, professional WPF developers should make it a practice to learn the differences in features and performance of each panel and choose the best one for a particular layout scenario.
In general, you should first try a StackPanel. If you can accurately lay out your Window with StackPanels without a deep nested web of them, they are the best way to go. They are much faster than Grids in both measurement of elements and layout/arrangement.
There are several other panels included in WPF. These are the most common, ranked from fastest to slowest (in general):
- Canvas
- StackPanel
- WrapPanel
- DockPanel
- Grid
This ranking is based on the accepted answer in this StackOverflow question. If you're interested in reading more about each of the panels and how they 'stack' up in different scenarios, I highly recommend reading the question and top answer.
Cheers!
Thursday, March 30, 2017
WPF Tip #7 - Freeze WPF Freezable Objects from Code
If mySimpleImage.CanFreeze ThenYes, I'm giving VB some love in today's tip.
' Makes the vector image frozen.
mySimpleImage.Freeze()
End If
Checking CanFreeze is necessary because not all Freezable objects can be frozen at every point in a WPF application's lifecycle. If Freeze() is called on an object that cannot currently be frozen, an exception will be thrown.
Monday, March 27, 2017
WPF Tip #6 - Freeze Vector Image Resources
A Freezable is a special type of object that has two states: unfrozen and frozen. When unfrozen, a Freezable appears to behave like any other object. When frozen, a Freezable can no longer be modified.
A few examples of WPF Freezable objects are Brushes, DrawingImages and Animation KeyFrames. If an application uses any of these resources and they are not going to be modified, they should be frozen. This will improve the performance of the application, as less processing will be used to re-render graphical elements.
Here is a quick example of Freezing a DrawingImage. Consider vector graphics used in fixed-size elements on a window (toolbar buttons, for example). These are good candidates to be frozen.
<DrawingImage x:Key="SimpleImage" presentationOptions:Freeze="True">
<DrawingImage.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="Black">
<GeometryDrawing.Geometry>
<EllipseGeometry Center="50,50" RadiusX="50" RadiusY="50"/>
</GeometryDrawing.Geometry>
<GeometryDrawing.Pen>
<Pen Brush="Red" Thickness="2" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingGroup.Children>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
Happy coding!
Wednesday, March 22, 2017
WPF Tip #5 - Data Binding with IMultiValueConverter
In Tip #4, we examined the use of IValueConverter with WPF binding. If you are using MulitBinding, a converter class that implements IMultiValueConverter is needed.
Like the IValueConverter, the class must implement Convert and ConvertBack methods. The difference being the multiple values come in as an object[] parameter in Convert() and go back out as an object[] return value in ConvertBack(). The following example takes two string values as input and returns them concatenated with a pipe '|'. It will convert them back using the Split function, assuming your text value contains no other pipes.
public class TextAppendMultiConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return String.Concat(values[0], "|", values[1]);
}public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return (value as string).Split('|');
}
}
This code will use the converter in a WPF TextBox's Text property MultiBinding.
<TextBox>
<TextBox.Text>
<MultiBinding Converter="{StaticResource TextAppendMultiConverter}" FallbackValue="Busy loading...">
<Binding Path="IntroText"/>
<Binding Path="ContentText"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
The FallbackValue will be displayed if the converter fails or data is unavailable in the attached DataContext.
Next time, we will shift gears away from data binding. Happy coding!