Friday, August 19, 2011

Routed Commands in WPF


What are Commands?


Commands are introduced with WPF and have great features. Commands are more abstract and loosely coupled than events. Commands are looks similar to events but it keeps action separate from UI. Another interesting feature of command is it can check whether command can execute or not by implementing CanExecute method. Commands also support input gestures (Keyboard shortcut like Ctrl+K etc.). 

What is RoutedCommand?


In WPF, Command object must inherit from ICommand interface. Routed command implements ICommand interface. Routed command can bubble through the element hierarchy. Routed commands provides certain features like 
  • Routed command source can be decoupled from command target.
  • Routed command allows attaching input gestures (Keyboard shortcut, Mouse input etc.).
  • Routed command enables or disables UI control based on command’s availability.

Important members of Routed command


Execute – This method contains code or logic to be executed when command executes.
CanExecute – This method checks whether command is available or not if available then it returns true otherwise retuns false.
CanExecuteChanged – This event is raised when the value of CanExecute changes.

Built-in commands


WPF provides 100+ built in commands. You can easily plugin those commands in your application. You can integrate those commands with some of WPF controls which exposes Command property like Button, Checkbox, MenuItem etc. All built in commands are organized and exposed in ApplicationCommands, ComponentCommands, MediaCommands, NavigationCommands, EditingCommand classed. If you want to use commands like Cut, Copy and Paste you can easily integrate within application without adding additional code. If you want add customize logic you can create those commands by implementing ICommand interface and customize logic in Execute and CanExecute method. But built-in commands can be implemented without much additional code. Let’s look on below mentioned XAML code.

<StackPanel>
    <TextBox x:Name="EmployeeName" Height="30" Margin="5" />
    <Button Content="Copy"
            Command="ApplicationCommands.Copy"
            CommandTarget="{Binding ElementName=EmployeeName}"
            Height="30" Width="150" Margin="5"  />
    <Button Content="Paste"
            Command="ApplicationCommands.Paste"
            CommandTarget="{Binding ElementName=EmployeeNameDuplicate}"
            Height="30" Width="150" Margin="5"  />
    <TextBox Name="EmployeeNameDuplicate" Height="30" Margin="5" />
</StackPanel>














In above example, Copy button implements ApplicationCommands.Copy command and command target is EmployeeName textbox. So when user enters and selects text that time only for copy button is enable otherwise its disabled. Paste button implements ApplicationCommand.Paste command and command target is EmployeeNameDuplicate textbox so when user clicks on paste button after copy it will paste text in textbox.

How to create custom Routed Command?


Sometimes you might need to create your own custom command. Below mentioned code demonstrate how to create custom routed command.


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)
{
    //Return true or false based on command availablity.
    e.CanExecute = true;
}

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    //Write custom logic
    MessageBox.Show("My Command executed...");
}

 


In above example, when user clicks on ‘ClickMe’ button it will execute MyCommand and display Messagebox and also when ALT + C key pressed the command will execute.


As per the code, custom routed command named MyCommand is created. In 
XAML command binding is declared. Command binding specifies Command, Execute and CanExecute method. Command is also specified on Button’s command property and also attached as static reference.


In code behind First declared routed command and with declaration command name, owner type and input gestures can be specified. I have added KeyGesture in Window’s loaded event and also implement Execute and CanExecute methods.

See also

1 comment: