Routed Command In WPF

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 

  1. <Window.CommandBindings>  
  2.     <CommandBinding Command="{x:Static local:CustomRoutedCommand.MyCommand}" Executed="CommandBinding_Executed" CanExecute="CommandBinding_CanExecute" /> </Window.CommandBindings>  
  3. <Grid>  
  4.     <Button Command="{x:Static local:CustomRoutedCommand.MyCommand}" Name="myButton" Content="Click Me!" Width="150" Height="40" />   
  5. </Grid>   

Code behind 

  1. public static RoutedCommand MyCommand = new RoutedCommand("MyCommand"typeof(CustomRoutedCommand));  
  2. void CustomRoutedCommand_Loaded(object sender, RoutedEventArgs e) {  
  3.     MyCommand.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt));  
  4. }  
  5. private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) {  
  6.     //Return true or false based on command availablity.  
  7.     e.CanExecute = true;  
  8. }  
  9. private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {  
  10.     //Write custom logic  
  11.     MessageBox.Show("My Command executed...");  
  12. }   

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.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now