In the previous posts we saw the basic of our project, the model (domain entities) and a simple repository.

Note: please note that the sample I wrote about an agnostic UnitOfWork is just to show you a simple pattern to handle L2S but it can be done better.

The ViewModel.

What is the view model? Well the simplest explanation is enclosed in this definition: the view model should be the datacontext of our view. It should provide the commands, the observable collections used in the view and the error logic.

Before starting to view how to build the basic abstract class for the viewmodel I want to talk about the Relay Command and the Routed Command and their differences.

Routed or Relay command?

I have found a useful explanation here, in the Josh Smith blog. Routed events are events designed to work in a tree of elements. When a user click the text over a button, the even travels over the tree until it will find the Click event of the chrome button.  This is how a button implements a routed events:

The commands in WPF represent a more independent action from their user interface. Also WPF and NET expose a default set of commands that we can easily handle in our application, like:

Application command, ComponentCommand, MediaCommand, NavigationCommand and EditingCommand.

They inherit all, from the ICommand interface. So for each command you want to implement, it should inherit from ICommand in this way:

So it becomes simple to understand that we should have a View Model abstract class that contains an abstract implementation of a collection of ICommand. Then we can inherits each view model from this one!

So our conclusion is that:

The key difference is that RoutedCommand is an ICommand implementation that uses a RoutedEvent to route through the tree until a CommandBinding for the command is found, while RelayCommand does no routing and instead directly executes some delegate. In a M-V-VM scenario a RelayCommand (DelegateCommand in Prism) is probably the better choice all around.

The final implementation of the Relay command should be something like:

image

In the next tutorial we will see how to build the abstract layer for a basic view model with a basic collection of relay commands.

Tags:

Comments are closed.

Post Navigation