#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);
Follow

Get every new post delivered to your Inbox.

Join 365 other followers