WPF and the command pattern
Posted by: Mark Shurmer
You may (or may not) have noticed, but WPF doesn’t implement the command pattern as per the GOF definition.
Instead it uses the term command to use the same definition in multiple places, but have the functionality specified locally.
As an example is worth a 1000 words (as true now as when confucius said something similar):
With WPF you can define a user defined command, normally as a static member, eg.
public static RoutedUICommand Exit = new RoutedUICommand(”E_xit”, “Exit”, typeof(RoutedCommands));
Then from any xaml you can reference that command. So lets say you have a menu item and a toolbar item that exit the application from the main window, and (for some bizarre reason) a button on a dialog. All three can reference the same command definition
<MenuItem Command=”{x:Static gc:RoutedCommands.Exit}” />
<Button Content=”_Exit” Command=”{x:Static gc:RoutedCommands.Exit}” />
The button definition above is used in both the toolbar and the dialog, and pressing all three does the same - well at this stage precisely nothing, as we haven’t told WPF to do anything, but we have achieved our goal of a common command definition.
To get around that, add a command binding to the main form and the dialog and add handlers for the CanExecute and Executed events:
<CommandBinding Command=”{x:Static gc:RoutedCommands.Exit}” CanExecute=”Exit_CanExecute” Executed=”Exit_Executed” />
Now you can place your code in the handlers, and the buttons will be enabled if you set e.CanExecute = true in Exit_CanExecute and put App.Close() in the Executed handlers.
The downside is you have to repeat your code between the main form and the dialog - which leads on to the command pattern as defined by the Gang of Four - http://www.dofactory.com/Patterns/Patterns.aspx, which is detailed in the next post



You must be logged-in to post a comment. Log-in/Register