Warning : This page has been marked as an archive because the author consider that its content is no longer relevant.

This article supposes that you, the reader, knows about the concept of commands. Its goal is not to present in detail what is a command but more to show you how create and use them with nRoute.

In MVVM we often use commands to communicate between the view and the view model in order to put all the logic inside the view model and to enable the view to directly call it. The tasks the view model is responsible for is subject to interpretations, I consider that every line of code that is not manipulating graphical objects should not be inside the code-behind.

nRoute provides an implementation of commands with the ActionCommand and ActionCommand similar to the DelegateCommand that we often find in other frameworks.

Our application will have to display the current date in our main view and have a button we can click on it to refresh the date. This button will be bound to a command inside the view model which will be responsible for the update.

Here is the starting XAML code of our view:

<UserControl x:Class="nRoute_Commands.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:n="http://nRoute/schemas/2010/xaml"
    xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    mc:Ignorable="d">

    <i:Interaction.Behaviors>
        <n:BridgeViewModelBehavior />
    </i:Interaction.Behaviors>

    <StackPanel x:Name="LayoutRoot">
        <TextBlock Text="{Binding Date}" />
        <Button Content="Refresh" />
    </StackPanel>
</UserControl>

And here is the associated view model:

[MapViewModel(typeof(MainPage))]
public class MainWindowViewModel : ViewModelBase
{
    private DateTime? _date;

    public MainWindowViewModel()
    {
    }

    public DateTime? Date
    {
        get
        {
            return _date;
        }

        set
        {
            if (_date != value)
            {
                _date = value;
                NotifyPropertyChanged(() => Date);
            }
        }
    }
}

We have a textblock in our view bound to the Date property of our view model. Until now there’s nothing really difficult. You can also see that this button is not doing anything for the moment when we click on it.

We will now declare our command in the view model.

Let’s first add the following field (note that you must add the System.Windows.Input namespace to the view model):

private ICommand _refreshCommand;

We will now add a method that will initialize the command and use this method inside the constructor of the view model. Inside this method, we will initialize the command by passing it the method i twill have to call when invoked:

public MainWindowViewModel()
{
    SetupCommands();
}

private void SetupCommands()
{
    _refreshCommand = new ActionCommand(Refresh);
}

private void Refresh()
{
    Date = DateTime.UtcNow;
}

Now that this method is initialized we must expose it and for this we create the following property:

public ICommand RefreshCommand
{
    get { return _refreshCommand; }
}

Now let’s use it in our view.

In Silverlight 4, controls inheriting from the ButtonBase class have a Command property we can use to invoke a command when the button is clicked.

Here is how to declare that:

<Button Content="Refresh" Command="{Binding RefreshCommand}" />

It is possible to execute a command from an object that doesn’t have the Command property. Here is how we could have done it with the button (note that you must add a reference to System.Windows.Interactivity to your project to use this method).

<Button Content="Refresh">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <n:ExecuteCommandAction Command="{Binding RefreshCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

The main advantage with this method is that it enables us to choose which event will invoke the command (EventName property of the EventTrigger). You also see that we use the ExecuteCommandAction class of the nRoute framework to invoke the command. We could replace this by other behaviors such as NavigateAction or ExecuteControllerAction but this is out of the scope of this article.

About the choice of which method to invoke a method I would recommend to use the Command property whenever it exists and to use the EventTrigger for the rest.

Now if we execute our code and click on the button the date updates itself! You’ll need to add some other features to your application if you want to make money but anyway this shows you how to invoke commands. I hope this article will be useful. In the next article I’ll talk about how to pass parameters to your commands.

Comments