Routed command
Routed command can route (bubble/ tunnel) through the element hierarchy. Routed Command implements ICommand interface. It allows attaching input gestures like Mouse input and Keyboard shortcuts. Its source can be decoupled from target. WPF provides more than 100 built in commands. These commands can be integrated to WPF controls which have command properties like button, MenuItem, etc. EditingCommand, ComponentCommand, NavigationCommand, AplicationCommand are some of the classes which organize and expose built in commands.
You can create customized Routed commands by implementing ICommand.
You need to create static instance of type RoutedCommand. Then you need to implement _CanExecute and _Executed for the same.
XAML
- <Window.CommandBindings>
- <CommandBinding Command="{x:Static local:CustomRoutedCommand.MyCommand}" Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute" /> </Window.CommandBindings>
- <Grid>
- <Button Command="{x:Static local:CustomRoutedCommand.MyCommand}" Name="myButton" Content="Click Me!" Width="150" Height="40" />
- </Grid>
Code behind
- public static RoutedCommand MyCommand = new RoutedCommand("MyCommand", typeof(CustomRoutedCommand));
- void CustomRoutedCommand_Loaded(object sender, RoutedEventArgs e) {
- MyCommand.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt));
- }
- private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
-
- e.CanExecute = true;
- }
- private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
-
- MessageBox.Show("My Command executed...");
- }
Now in the above example, when the user clicks on ‘ClickMe’ button it will execute MyCommand and display Messagebox and also when ALT + D key is pressed the command will execute.