WPF: Command Factory


Many moons ago, I blogged about the Command System in WPF. Today I’m going to talk about a Factory Class that will create commands for you, taking in delegate functions as parameters. How this helps is reduce the amount of code you have to write, because the Command Factory takes care of that for you.

Read the rest of this entry »

Posted in WPF. Tags: . 2 Comments »

WPF Commands: Better approach to using ICommandSource


I originally wanted to write a post about using creating Command Source controls using ICommandSource but after looking at it on MSDN, I found quite a number of limitations with this approach…namely,

  • You need to create a custom control for every one that does not support taking a command source natively.
  • You can only bind one command at a time.
  • Your number of custom controls could grow fairly large very quickly, which makes maintenance of the code a horror, and not scalable.
  • The ICommandSource implementation code will be repeated in most of your custom controls, which is not a good option. I have thought about abstracting that out using a base class (that implements ICommandSource), but the problem is that your custom control needs to inherit the original WPF control (e.g. Slider, ListView), and multiple inheritance is not allowed in C#, so there goes my idea.

Better Approach

I pondered to myself….there has to be a better way to do this, and after much searching, I found a great article which suggest an alternate and better approach. I came across the solution in a blog post (WPF Commands Everywhere) by Tomer Shaman. The idea behind it is by using custom-written Command Source Trigger classes and using the WPF Attached Properties mechanism. This allows us to define the Command Source Triggers in XAML, and the author introduces two kinds of triggers, one for Routed Events and one for Property Changed. When a routed event is triggered or property value is changed, the Command that is hooked up will be triggered, essentially emulating the ICommandSource behaviour, but without all the messy/repetitive code. This is a snipplet of the XAML code from Tomer’s blog post.

<ListView x:Name="list"
		  SelectedIndex="-1"
		  DockPanel.Dock="Top"
		  ItemsSource="{Binding Emails}"
		  IsSynchronizedWithCurrentItem="True"
		  Height="100">
	<ts:CommandSource.Trigger>
		<ts:CommandTriggerGroup>
			<ts:EventCommandTrigger RoutedEvent="UIElement.PreviewMouseLeftButtonUp"
									Command="{Binding Path=DownloadEmail}"
									CustomParameter="{Binding ElementName=list, Path=SelectedValue}" />

			<ts:EventCommandTrigger RoutedEvent="UIElement.PreviewMouseRightButtonUp"
									Command="{Binding Path=MarkAsRead}"
									CustomParameter="{Binding ElementName=list, Path=SelectedValue}" />

			<ts:EventCommandTrigger RoutedEvent="UIElement.PreviewMouseLeftButtonDown"
									Command="{Binding Path=OpenEmail}"
									CustomParameter="{Binding ElementName=list, Path=SelectedValue}" />
		</ts:CommandTriggerGroup>
	</ts:CommandSource.Trigger>
</ListView>
....
<Expander IsExpanded="{Binding Path=DummyProperty}" Header="Contact">
	<ts:CommandSource.Trigger>
		<ts:PropertyCommandTrigger Property="Expander.IsExpanded"
					   Value="True"
					   CustomParameter="{Binding}"
					   Command="{Binding Path=DownloadContact, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" />
	</ts:CommandSource.Trigger>
</Expander>

In the code behind, the Commands (DownloadEmail, MarkAsRead, OpenEmail) are instantiated and exposed with public getters for databinding in XAML. I strongly suggest that you go over to Tomer’s blog post and have a read, and download the full code for this implementation. It will start to make sense once you start digging into it.

I personally feel that this implementation is much cleaner, reusable and just brilliant. If you agree, do go over to Tomer’s blog and leave him a ‘thank you’ or comment, I did. 🙂

Share this post:
Posted in WPF. Tags: . Leave a Comment »

WPF Commands Part 3: Custom RoutedUICommand


Welcome to Part 3 of WPF Commands. This will be the second last of the Basics for WPF Commands. For this entry, we will be looking at creating a custom RoutedUICommand, and how to make use of CommandTarget and CommandParameter properties.

First of all, you will typically need to create custom commands if the ones you get out of the box from WPF is insufficient. I would not think that this is a common scenario, but it would be good to know how to do it. If you need to do this, I recommend putting your custom controls into a separate class, similar to WPF. Let’s call our custom class CommandLibrary.

public static class CommandLibrary
{
    private static RoutedUICommand add = new RoutedUICommand("Add", "Add", typeof(CommandLibrary));

    private static RoutedUICommand remove = new RoutedUICommand("Remove", "Remove", typeof(CommandLibrary));

    public static RoutedUICommand AddListItem
    {
        get { return add; }
    }

    public static RoutedUICommand RemoveListItem
    {
        get { return remove; }
    }

}

Read the rest of this entry »

WPF Commands Part 2: Command Bindings and Gestures


Welcome to Part 2 of WPF Commands. If you have not looked at my previous entry talking about the basics, you should have a look at it here. That should set you up for understanding this example.

What are Command Bindings? Simply put it, it allows us to specify the commands that a particular control will be listening to, and the event handlers that will implement the command logic. If you remember that all commands in WPF implement ICommand interface, it defines two methods CanExecute and Execute. Controls (ones that can handle input focus) typically understand how to execute commands on themselves. So now, how do we “make” a control understand a different command?

For example, I want to be able to make a TabContainer change tabs on a button click. How do we achieve that? No brainer here, with Command Bindings. To make it more exciting, WPF also allows us to hook up commands with Input Gestures. It’s an abstract class, and we will be dealing with two types of gestures, namely KeyGesture and MouseGesture. Examples of mouse gestures are left button click, scroll wheel click and key gestures speak for themselves. Both kinds of gestures allow us to also define an optional control modifier, e.g. Control + Left Button Click, or Shift + C key. A Command Binding allows us to wire up a control to a custom Command, or WPF’s library of Commands, or Input Gestures.

The sample application will be the same as my previous post, but we will be using the Buttons and key gestures to navigate between the tabs on the Tab Container. Please take a look at this video of this demo.

wpfcommand12

Read the rest of this entry »

WPF Commands Part 1: Basics


WPF has introduced to us developers a wide new range of concepts and useful features, one of which is the Command System. It is based on the infamous Command Pattern, with a slight twist. It’s basically utilizing the Command Pattern with routing facility, as termed by Microsoft as the Routed Command System. Examining this closely, it’s similar to the Routed Event system that is inherent in WPF, and they used it for sending Commands for the UI controls to trigger a certain behaviour.

In one of my previous projects using WinForms and Model-View-Presenter (MVP) pattern, we faced the challenge of implementing a TreeView that is capable of triggering certain behaviours at different TreeNode Presenters. One of the developers came up with a very interesting implementation of using the Command Pattern and a variation of the Visitor Pattern. It was complicated, being a fresh developer, it took me hours to understand. Later he told me this pattern he used is known as the Double Dispatch pattern, which I later read about in a Design Pattern book. Now looking at Routed Command has reminded me of this, and is a similar implementation of the Double Dispatch.

It’s very interesting to see that Microsoft has started using a lot of Patterns in WPF, like Command and Observer. MS has also introduced a slight varation of the MVP, called Model-View-ViewModel pattern alongside the Pattern and Practices guide. In my opinion, this is a breath of fresh air, and .NET developers can no longer be “excused” from knowing about using and understanding patterns and how it helps to write elegant code, and decoupling your application.

Read the rest of this entry »