LA.NET [EN]

Apr 01

Silverlight: getting started with commands

Posted in Silverlight      Comments Off on 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.