Thursday, February 26, 2009

Attaching application commands to User controls

WPF allows attaching of Application commands to user controls so that your control can respond to a command without any additional code.
You have to use the System.Windows.Input.CommandManager to register an instance of the System.Windows.Input.CommandBinding class for each member of System.Windows.Input.ApplicationCommands you need to support in your user control. The CommandBinding specifies the type of command you want to receive notification of, specifies an event handler to determine when the command can be executed, and specifies another event handler to be called when the command is executed. These event handlers are called the CanExecute and Executed event handlers.
For example if you want to launch the Print dialog from your user control when the user presses Ctrl+P. Then you have to register the ApplicationCommands.Print member in your user control. The below given sample code shows how to do that.

CommandManager.RegisterClassCommandBinding(
typeof(FileUploader),
new CommandBinding(
ApplicationCommands.Print,
(x, y) => new PrintDialog().ShowDialog(),
(x, y) => y.CanExecute = true));

1 comment:

Timothy said...

So once you have done this how do you tell the user control to print itself if it contains several textblocks, dropdowns and textboxes?