Exercise 2: Commands and the ViewModel
One of the goals of a ViewModel is to minimize the amount of code in the view, in order to facilitate unit testing. The first part of this lab illustrated how data binding makes it possible for a ViewModel to update properties of elements in the view. But what about when we need things to flow in the other direction? How does the ViewModel discover user activity such as button clicks?
One solution is to have ordinary event handlers in the view’s code behind, and have those call into methods on the ViewModel. For example, the ViewModel could define an OnRegisterButtonClicked method to be called by the view. While this doesn’t quite meet the ideal of avoiding all code in the view, that’s not a huge problem, because the only code required in the view is a single method call through to the ViewModel. However, Silverlight 4 introduces a feature that was previously only available on the desktop with WPF, which can help us do better: commands.
Commands are an abstraction representing an operation that can be invoked through some user action such as a button click. You can data bind a Button’s Command property to a command object exposed by a ViewModel, which avoids the need for a Click handler in the code behind. The button is able to invoke the command directly. But it adds an additional benefit: the command abstraction (represented by the ICommand interface) also supports the idea that a command may be enabled or disabled from time to time. This means the ViewModel also has a way of controlling whether the button associated with a command is enabled or disabled. (Of course, we could have done that by offering a bool property on the ViewModel and binding a button’s IsEnabled property to that. But commands let us kill two birds with one stone: by binding just the one property: Button.Command, we can have the ViewModel both handle button clicks and set the enabled state of the button.
In this exercise, we’ll use this technique for the Register and Unregister buttons you added in the previous part.
Add Authentication Based Custom Domain Service Methods
Implement the Bindings