#343 – Associating Multiple Controls with the Same Command
July 15, 2011 Leave a comment
One benefit of using commands in WPF, as opposed to writing event handlers, is that it’s easier to link multiple controls to a single command. With commands, you can create a single command object, bind it to a method, and then associate the command with more than one control by setting the Command property of each control.
In the example below, we associate the ApplicationCommands.Open command with both a Button and a MenuItem.
<Window.ContextMenu>
<ContextMenu>
<MenuItem Header="Open" Command="ApplicationCommands.Open"/>
</ContextMenu>
</Window.ContextMenu>
<StackPanel>
<Button Content="Open" Command="ApplicationCommands.Open" HorizontalAlignment="Center" />
</StackPanel>
In the code-behind, we still only have to create a single CommandBinding instance.
public MainWindow()
{
this.InitializeComponent();
CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_CanExecute));
}
public void Open_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Open file code goes here");
}
public void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true; // Can we open file?
}
