WPF Reflections

Oct 19 2007   11:14AM GMT

Command design pattern and WPF

Mark Shurmer Profile: MarkWPF

Tags:
SMTP

For an good explanation of GOF version, see http://www.dofactory.com/Patterns/PatternCommand.aspx

How does the command pattern differ from the WPF vision of commands?
Well the most striking difference is that the command pattern is there to provide common functionality for all commands. For example you could add logging or undo/redo functionality into the inheritance chain.
As part of that, the standard way of using the commands in WPF means you have to duplicate the CanExecute and Executed code in different windows. Of course all those places could call through to a common method, but that’s getting messy!

So how do you implement the command pattern functionality in WPF?
Firstly you need to subclass the RoutedUICommand class to add your specific CanExecute and Execute methods, see below.
One problem that is left is how you add a binding for your command to the right place in the visual tree, for example the main form or another dialog or a menu etc etc. There is a method on this class, called BindToElement, that you can call from your code:

cmdExit.BindToElement(frm); 
 

public class RoutedCommandBase : RoutedUICommand
{
private CommandBinding binding
public RoutedCommandBase(string descr, string name, Type owningType)
: base(descr, name, owningType)
{
binding = new CommandBinding(this, Execute, CanExecute);
CommandManager.RegisterClassCommandBinding(typeof(App), binding);
}
public CommandBinding Binding
{
get { return binding; }
set { binding = value; }
}
public virtual void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
}

///
/// Run the command
///
///
///
public virtual void Execute(object sender, ExecutedRoutedEventArgs e)
{
}

public virtual void BindToElement(UIElement ele)
{
if(ele != null)
ele.CommandBindings.Add(binding);
}

}

 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: