#11 – Commands

WPF provides support for commands, where a command is an object that performs a particular task independent from the GUI element that initiated the task.  The main purpose of commands is to move code common to multiple controls into a central location, out of the event handlers for the individual controls.  This allows multiple controls to invoke the same command logic.

You create a command by binding a command object to your code.

WPF includes a library of pre-created commands for common tasks like Copy, Cut and Paste.  These command objects are merely placeholders–you still have to write the code that does the actual work for each command.

Here’s an example of a Button being bound through a built-in command to custom code.

 <Button Content="New" Command="ApplicationCommands.New"/>
 // Create binding--which binds the command to your code
 CommandBinding binding = new CommandBinding(ApplicationCommands.New);
 binding.Executed += new ExecutedRoutedEventHandler(CommandNew_Executed);
 this.CommandBindings.Add(binding);
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #11 – Commands

  1. Pingback: #1,078 – Defining a Command Binding Using Lambda Expressions | 2,000 Things You Should Know About WPF

  2. Pingback: #1,082 – Adding CommandBindings to Individual UI Elements | 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: