Silverlight: getting started with commands

Silverlight 4.0 added the notion of command. In practice, a command is any object which implements the ICommand interface (btw, this is another of those interfaces which have been imported from WPF). Currently, the interface exposes the following members:

  • Execute: this method is responsible for executing the logic  associated with this command;
  • CanExecute: this method should return true if the command is enabled (that is, if the command can be executed);
  • CanExecuteChanged: this event is raised when the value of the CanExecute property changes.

Before going on, I’d like to poin out that, unlike WPF, Silverlight doesn’t really define any default commands (I’m just saying this because if you’re coming form WPF, you might expect to find some of the default commands that exist there; however, that is not the case).

It’s important to understand what commands give you. Before going on, I should say that you could (almost) get away without commands since you can always handle events and add your custom logic to them. However, commands give you superior support for encapsulating logic and reusing them in several places. This is especially true because several Silverlight control’s add logic for interacting with commands.

For instance,all Silverlight buttons (ie,all controls that inherit form ButtonBase) expose a Command (dependency) property which you can set to any object which implements the ICommand interface. As you might expect, the button will try to execute the command in response to any click that is performed over it. Besides that, it will also keep its IsEnabled property in sync with the command’s CanExecute property (this info is updated in response to the CanExecuteChanged event of the command). As you can see, there really is no reason for skipping commands, right?

Notice that you can reuse commands in several places. For instance, Fredrik Normen shows in this post how you can reuse the command concept to support the MVVM pattern. And that’s all for now. Stay tuned for more on Silverlight.


~ by Luis Abreu on April 1, 2010.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: