Monday, March 21, 2011

WPF Commands

Just write some note summary:

.Net framwork has several predefined Commands, they are static objects which are the following 5 static classes:
1. ApplicationCommands
2. EditingCommands
3. ComponentCommands
4. MediaCommands
5. NavigationCommands

Some of the predefined Commands don't need CommandBinding, for instance: ApplicationCommands.Cut, so we can write in xaml:

< Button Command="ApplicationCommands.Cut" CommandTarget="{Binding ElementName=myTextBox}" >

(Button, MenuItem Controls are Inherited from ICommandSource interface and let them to be able to associated with the Command property.

Some of the Predefined Commands Still need CommandBinding, for instance: ApplicationCommands.Help.


Like events, Commands also bubble up to the visual tree, for instance we have a visual tree

Window
|
|__Grid
|
|__Button

We can have the CommandBindings under the button node, we can also have the CommandBinding at Grid or Window node.

When do the CommandBinding, we specify the Command Excuted event handler to execute the code when Command is invoked. We can also specify the CanExecute event handler to enable or disable the command. Notice when a command is disabled, the UIElement associated with the command is disabled too.

We can create custom Command as well. WPF support Routed Command. (Notice SilverLight doesn't support this).

We just need to create a RoutedCommand static instance. Sometimes we may need to use singleton patten to create a Custom Command Class, for instance:

public class MyCommands
{
private static RoutedCommand launch;

static MyCommands()
{
launch=new RoutedCommand();
}

public RoutedCommand Lauch
{
get
{return lauch;}
}
}

SilverLight doesn't support RoutedCommand. But good thing is that SL4 support ICommand interface(Delegate/Relay Command).

For the ICommand interface, please read MSDN, it exposes 3 memembers:

Method:
CanExecute
Executed

EventHandler:
CanExecuteChanged

ICommand interface is more useful than RoutedCommands actually, especially in M-V-VM modle. We can set the Delegate Command as a property.

Here I just write some sample code use(I just placed the Delegate Command as a static class property in my sample)

Predefined Command (Doesn't need Command Binding, the eventhandler is predefined)

Predefined Command need Command Binding

Routed Command

Delegate Command(ICommand)

The sample code can be downloaded Here.

No comments: