WPF Reflections

Oct 18 2007   12:43PM GMT

WPF and the command pattern



Posted by: MarkWPF
Tags:
WPF

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: