Creating WPF application with Microsoft.Toolkit.Mvvm library

WPF

The "Microsoft.Toolkit.Mvvm" library simplifies various tasks of creating and maintaining view models if the WPF application is built with MVVM design

There are a few scenarios we would like to address:

  • The view (control) raises routed events.
    • In this case we need to call a command on the ViewModel.
      Some controls run a command triggered by a specific event. E.g a button calls a command on click event. Other events should be treated separately with the Interactivity assembly.
  • The view (control raises a standard event.
    • Here we need to subscribe to the event in the code behind and send a message using the MVVM toolkit messaging mechanism.
  • The view model needs to call a method of a control.
    • We need to create a custom behavior which attaches the control methods to the view model.
  • The view model manages properties and their state is reflected in the View.
    • A standard implmentation of INotifyProperty changed, which is more simple with the MVVM toolkit.
   

First, let's see how to convert routed events into commands.

Inherit the view model from "ObservableObject".

Bind events to commands in the view model:

reference System.Windows.Interactivity by:

Add Reference -> Assemblies -> Extensions

Add interactivity namespace to the XAML control declaration:


xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

Use like this:


<i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"/>
        </i:EventTrigger>
 </i:Interaction.Triggers>

How to use the messaging mechanism

Create a message class:


public class NewDataMsg: IValueChangedMessage
{
    public NewDataMsg(IData data): base(data) {}
}

Then in the receiving class:


public class SomeViewModelClass: ObservableObject, IRecipient
{
    public SomeViewModelClass()
    {
        WeakReferenceManager.Default.RegisterAll(this);
    }

    public Receive(NewDataMsg msg)
    {
        /* Do something with the data */
    }
}

In the class which sends the message:


WeakReferenceManager.Default.Send(new NewDataMsg(someData));

Properties in the View Model set for binding


private string myProp;

public string MyProp
{
    get => myProp;
    set => SetProperty(ref myProp, value);
}

Post a Comment

Previous Post Next Post