Language: EN

mvvm-light-un-framework-ligero-para-mvvm-en-net

MVVM Light, a lightweight framework for MVVM in .NET

Mvvm Light is a lightweight framework for implementing the MVVM design pattern in .NET Framework applications, quite popular in WPF developments.

Implementing MVVM (Model View ViewModel) in WPF without a framework forces us to implement a large number of tools ourselves. There are multiple frameworks available to make our lives easier.

Among the different alternatives, MVVM Light stands out as a lightweight, simple framework with a smooth learning curve.

Although it lacks certain features of more powerful frameworks, MVVM Light is minimally intrusive and yet provides most of the usual tools in an MVVM pattern. In this post, we will take a quick look at its main features.

Installation

The installation of MVVM Light is available through a Visual Studio Extension (2013, 2015, and 2017). This extension adds templates for creating a Scaffold of an application with MVVM Light, and a few snippets to facilitate programming.

mvvm-light-extensions

It is also possible to add MVVM Light to an existing solution through the NuGet package manager.

mvvm-light-nuget

MVVM Light Components

As we were saying, MVVM Light provides most of the usual tools in an MVVM pattern. Let’s see some of these features.

RelayCommand

MVVM Light provides the implementation of ICommand in its RelayCommand object, both with parameters and without parameters, and with the possibility of enabling/disabling the command through a function (canExecute)

public class RelayCommand<T> : ICommand
{
  public RelayCommand(Action<T> execute);

  public RelayCommand(Action<T> execute, Func<T, bool> canExecute);
}

Here we would have an example of use, where we define the command as a property of our ViewModel.

public RelayCommand<T> MyCommand { get; set; }

In the constructor of the ViewModel, we instantiate the command.

MyCommand = new RelayCommand(myAccion);

Which points to a function that executes the command.

myAccion(T);

Event to command

We also have the usual ‘Event to command’, which allows routing an event to a command. Its use would be as follows.


<i:interaction.triggers>
  <i:eventtrigger eventname=""TextChanged"">
    <mvvm:eventtocommand command=""{Binding" searchcommand,="" mode="OneWay}"">
  </mvvm:eventtocommand></i:eventtrigger>
</i:interaction.triggers>

INotifyPropertyChanged

Of course, MVVM Light provides its implementation of INotifyPropertyChanged, which allows informing the UI of changes in the bound property.

public virtual void RaisePropertyChanged<T>([CallerMemberName] string propertyName = null, T oldValue = default(T), T newValue = default(T), bool broadcast = false);

IoC and Locator

MVVM Light also provides a simple implementation of an Inversion of Control (IoC), called SimpleIoC. For this, it is usual to generate our Locator, which registers the classes used.

public class ViewModelLocator
    {
        static ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

      SimpleIoc.Default.Register<MainViewModel>();
        }

        public MainViewModel Main
        {
            get
            {
                return ServiceLocator.Current.GetInstance<MainViewModel>();
            }
        }
    }

We will generally declare the Locator as a static resource in App.xaml as follows


<Application.Resources>
  <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</Application.Resources>

Finally, in the views, we can associate the DataContext with the different ViewModels as follows.

DataContext="{Binding Main, Source={StaticResource Locator}}"> 

Messenger

MVVM Light also implements a Messenger service that implements the PubSub pattern, allowing us to send messages between objects while keeping the coupling between classes weak.

For example, an object that wishes to send a message would use the following method.

public void SenderMethod()
{
  MessengerInstance.Send<NotificationMessage<string>>(new NotificationMessage<string>("Generic Value", "notification message"));
}

To receive it, one or more objects could subscribe to the messages, defining a callback function.


public RecievedMethod()
{
  MessengerInstance.Register<NotificationMessage<string>>(this, NotifyMe);
}

public void NotifyMe(NotificationMessage notificationMessage)
{
  string notification = notificationMessage.Notification;
  string genericValue = notificationMessage.Content;
  //do your work
}

DispatcherHelper

Finally, MVVM Light provides the DispatcherHelper class, which facilitates the use of tasks in the main UI thread.

This is initialized at the beginning of the application.

DispatcherHelper.Initialize();

And can be used to invoke actions in the UI process as follows.

DispatcherHelper.UIDispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(()=> { }));

As we can see, MVVM Light is a simple framework, but it provides the basic components necessary to implement MVVM. It is Open Source and available at https://github.com/lbugnion/mvvmlight