What’s new in MVVM Light V3

V3 of the MVVM Light Toolkit was released during MIX10, after quite a long alpha stage. This post lists the new features in MVVM Light V3.

Compatibility

MVVM Light Toolkit V3 can be installed for the following tools and framework versions:

  • Visual Studio 2008 SP1, Expression Blend 3
    • Windows Presentation Foundation 3.5 SP1
    • Silverlight 3
  • Visual Studio 2010 RC, Expression Blend 4 beta
    • Windows Presentation Foundation 3.5 SP1
    • Windows Presentation Foundation 4 RC
    • Silverlight 3
    • Silverlight 4 RC

For more information about installing the MVVM Light Toolkit V3, please visit this page. For cleaning up existing installation, see this page.

New in V3 RTM

The following features have been added after V3 alpha3:

Project template for the Windows Phone 7 series (Silverlight)

This new template allows you to create a new MVVM Light application in Visual Studio 2010 RC and to run it in the Windows Phone 7 series emulator. This template uses the Silverlight 3 version of the MVVM Light Toolkit V3. At this time, only the essentials features of the GalaSoft.MvvmLight.dll assembly are supported on the phone.

New in V3 alpha3

The following features have been added after V3 alpha2:

New logo

An awesome logo has been designed for MVVM Light by Philippe Schutz.

DispatcherHelper class (in GalaSoft.MvvmLight.Extras.dll)

This class is useful when you work on multi-threaded WPF or Silverlight applications.

Initializing: The DispatcherHelper class must be initialized in the UI thread. For example, you can initialize the class in a Silverlight application’s Application_Startup event handler, or in the WPF application’s static App constructor (in App.xaml).

// Initializing in Silverlight (in App.xaml)

private void Application_Startup(
    object sender,
    StartupEventArgs e)
{
    RootVisual = new MainPage();
    DispatcherHelper.Initialize();
}


// Initializing in WPF (in App.xaml)

static App()
{
    DispatcherHelper.Initialize();
}

Verifying if a property exists

The ViewModelBase.RaisePropertyChanged method now checks if a given property name exists on the ViewModel class, and throws an exception if that property cannot be found. This is useful to detect typos in a property name, for example during a refactoring. Note that the check is only done in DEBUG mode.

Replacing IDisposable with ICleanup

The IDisposable implementation in the ViewModelBase class has been marked obsolete. Instead, the ICleanup interface (and its Cleanup method) has been added. Implementing IDisposable in a ViewModel is still possible, but must be done explicitly. IDisposable in ViewModelBase was a bad practice, because it supposes that the ViewModel is garbage collected after Dispose is called. instead, the Cleanup method does not have such expectation.

The ViewModelLocator class (created when an MVVM Light project template is used in Visual Studio or Expression Blend) exposes a static Cleanup method, which should in turn call each ViewModel’s Cleanup method. The ViewModel is free to override the Cleanup method if local cleanup must be performed.

Passing EventArgs to command with EventToCommand

The EventToCommand class is used to bind any event to an ICommand (typically on the ViewModel). In this case, it can be useful to pass the event’s EventArgs parameter to the command in the ViewModel. For example, for the MouseEnter event, you can pass the MouseEventArgs to a RelayCommand<MouseEventArgs> as shown in the next listings.

Note: Bringing UI specific classes (such as EventArgs) into the ViewModel reduces the testability of the ViewModel, and thus should be used with care.

Setting EventToCommand and PassEventArgsToCommand:

<Grid x:Name="LayoutRoot">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseEnter">
            <cmd:EventToCommand Command="{Binding MyCommand}"
                                PassEventArgsToCommand="True" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Grid>

Getting the EventArgs in the command

public RelayCommand<MouseEventArgs> MyCommand
{
    get;
    private set;
}

public MainViewModel()
{
    MyCommand = new RelayCommand<MouseEventArgs>(e =>
    {
        // e is of type MouseEventArgs
    });
}

Changes to templates

Various changes have been made to project templates and item templates to make them more compatible with Silverlight 4 and to improve their visibility in Visual Studio and Expression Blend.

Bug corrections

  • When a message is sent through the Messenger class using the method Messenger.Default.Send<T>(T message, object token), and the token is a simple value (for example int), the message was not sent correctly. This bug is now corrected.

New in V3

The following features have been added after V2.

Sending messages with callback

Certain classes have been added to the GalaSoft.MvvmLight.Messaging namespace, allowing sending a message and getting a callback from the recipient. These classes are:

  • NotificationMessageWithCallback: Base class for messages with callback.
  • NotificationMessageAction: A class with string notification, and a parameterless callback.
  • NotificationMessageAction<T>: A class with string notification, and a callback with a parameter of type T.

To send a message with callback, use the following code:

var message = new NotificationMessageAction<bool>(
    "Hello world",
    callbackMessage =>
    {
        // This is the callback code
        if (callbackMessage)
        {
            // ...
        }
    });

Messenger.Default.Send(message);

To register and receive a message with callback, use the following code:

Messenger.Default.Register<NotificationMessageAction<bool>>(
    this,
    message =>
    {
        // Do something
        
        // Execute the callback
        message.Execute(true);
    });

Messenger.Default can be overriden

The Messenger.Default property can also be replaced, for example for unit testing purposes, by using the Messenger.OverrideDefault method. All the public methods of the Messenger class have been made virtual, and can be overridden in the test messenger class.

Sending messages to interfaces

In V2, it was possible to deliver messages targeted to instances of a given class. in V3 it is still possible, but in addition you can deliver a message to instances that implement a certain interface. The message will not be delivered to other recipients.

Use the overload Messenger.Default.Send<TMessage, TTarget>(TMessage message) where TTarget is, in fact, an interface (for example IDisposable). Of course the recipient must register to receive the type of message TMessage.

Sending messages with a token

Messages can now be sent through the Messenger with a token.

  • To send a message with token, use the method overload Send<TMessage>(TMessage message, object token).
  • To receive a message with token, use the methods Register<TMessage>(object recipient, object token, Action<TMessage> action) or Register<TMessage>(object recipient, object token, bool receiveDerivedMessagesToo, Action<TMessage> action)

The token can be a simple value (int, string, etc…) or an instance of a class. The message is not delivered to recipients who registered with a different token, or with no token at all.

Renaming CommandMessage to NotificationMessage

To avoid confusion with ICommand and RelayCommand, the CommandMessage class has been renamed to NotificationMessage. This message class can be used to deliver a notification (of type string) to a recipient.

ViewModelBase constructor with IMessenger

The ViewModelBase class now accepts an IMessenger parameter. If this constructor is used instead of the default empty constructor, the IMessenger passed as parameter will be used to broadcast a PropertyChangedMessage when the method RaisePropertyChanged<T>(string propertyName, T oldValue, T newValue, bool broadcast) is used.

In the default ViewModelBase constructor is used, the Messenger.Default instance will be used instead.

EventToCommand behavior

The EventToCommand behavior has been added in V3. It can be used to bind any event of any FrameworkElement to any ICommand (for example a RelayCommand located in the ViewModel). More information about the EventToCommand behavior can be found here and here.

Updated the project templates to remove the sample application

The project template has been updated to remove the sample application that was created every time that a new MVVM Light application was created in Visual Studio or Blend. This makes the creation of a new application easier, because you don’t need to remove code before you can start writing code.

Bug corrections

Some bugs that were in Version 2 have been corrected:

  • In some occasions, an exception could be thrown when a recipient was registered for a message at the same time as a message was received.

New names for DLLs

If you upgrade an existing installation, you will need to change the reference to the DLLs in C:\Program Files\Laurent Bugnion (GalaSoft)\Mvvm Light Toolkit\Binaries. The assemblies have been moved, and the versions for Silverlight 4 and for WPF4 have been renamed, to avoid some confusion. It is now easier to make sure that you are using the correct DLL.

WPF3.5SP1, Silverlight 3

When using the DLLs, make sure that you use the correct versions.

WPF4, Silverlight 4

When using the DLLs, make sure that you use the correct versions.

 

Print | posted on Tuesday, March 16, 2010 4:42 AM

Feedback

# re: What’s new in MVVM Light V3

left by Pencho at 3/25/2010 9:13 PM Gravatar
Hi Laurent, first of all great work !. I have the following small issues with the EventToCommand in wpf4. I want to handle the SizeChanged event of UIElement in the ViewModel, that's why I am using RelayCommand<SizeChangedEventArgs>. Everything works perfect, except the fact that the first the SizeChanged event is raised, the RelayCommand IS NOT called. I am pretty sure that when the SizeChanged is raised the RelayCommand is already wired up!!! Is there something that I am missing ?
Best Regards

# re: What’s new in MVVM Light V3

left by Laurent at 3/25/2010 10:11 PM Gravatar
Hi Pencho,

This bug has been reported a couple of times already. I didnt however hav time to look into it. It is on my list. Please stay tuned, thanks.

Cheers,
Laurent

# re: What’s new in MVVM Light V3

left by CuriousGeorge at 3/26/2010 7:15 AM Gravatar
Laurent, I love the concept of NotificationMessageAction<>. But could it be easily extended to support any message type, rather than just string? In my app I am looking to wrap all calls to MessageBox.Show with Messenger (so I can use it in a ViewModel) but in some cases need to pass something other than string and also receive a result back (in the case of a Yes/No MessageBox).

Any thoughts?

# re: What’s new in MVVM Light V3

left by Laurent at 3/26/2010 9:04 AM Gravatar
Hey George,

Sure, that is the idea in fact. The class hierarchy is like that:

- MessageBase
- NotificationMessage
- NotificationMessageWithCallback
- NotificationMessageAction<TCallbackParameter>

I did it this way because passing string commands is a very common scenario. However you can easily create your own message type with callback, inspiring yourself from those ones. Alternatively you can subclass the NotificationMessageAction<TCallbackParameter> and make a GenericMessageAction<TContent, TCallbackParameter>. Does that make sense?

Cheers,
Laurent

# re: What’s new in MVVM Light V3

left by Bob Baker at 3/28/2010 5:32 AM Gravatar
First, of all, a great job, Laurent! I had a practices question around the ViewModelLocator. At what point do you think one should move to a heavier (creamier, lol) framework as far as the number of views/viewmodels is concerned. I can see where the ViewModelLocator class could get quite large with a lot of similar code for anything over 5-6 ViewModels. Am I missing an approach here that night make things a little simpler and more manageable (e.g., multiple locator classes organized by appication function)? Thanks again for an incredible framework.

# re: What’s new in MVVM Light V3

left by Matt Casto at 4/1/2010 3:11 AM Gravatar
I'm trying out MVVM Light for a new project, and love it so far.

Your get started page and sample explained both say that creating a new MVVM Light project should create the sample application, but all I get is a single static view. Is there a separate sample application available to download that I'm just not finding?

Thanks again!

# re: What’s new in MVVM Light V3

left by Laurent at 4/1/2010 8:59 AM Gravatar
Yo Matt,

The project template used to create a sample app. I removed that for two reasons: 1) it was annoying to always have to delete everything you didn't use to start a new project and 2) the sample app was not very interesting.

I forgot to change the doc, thanks for the pointer. The plan now is to create a reference app that I will publish, to show all the features of MVVM Light at use, together with a documentation page. I will do that soon. In the mean time, download the sample code for my MIX10 session and check the demo named "Mix10.MvvmDemo2 - End". It is a nice SL4 example using WCF, RelayCommand, ViewModelBase and dependency injection in the MainViewModel, and is fully blendable.

Cheers,
Laurent

# re: What’s new in MVVM Light V3

left by Matt Casto at 4/1/2010 9:08 AM Gravatar
Thanks for responding. Yes, I downloaded your samples from your MIX10 talk and I've been using them for reference.

What I was specifically looking for was examples of each type of Messenging and EventToCommand. I've figured out most of it by now, but it will be great to have a reference application containing all of that.

I'm assuming you'll host the reference application on your CodePlex project. If so, I'd be happy to contribute.

# re: What’s new in MVVM Light V3

left by Laurent at 4/1/2010 9:26 AM Gravatar
Very cool. Thanks Matt, I will get back to you. A bit overloaded right now, but it is definitely a plan.

Cheers,
Laurent

# re: What’s new in MVVM Light V3

left by Joe at 4/6/2010 7:25 AM Gravatar
Well - great stuff but a example application would be really great. I was not planing to install Silverlight but it seem like I have to to get an sample app. Has anybody else an sample app to share?

# re: What’s new in MVVM Light V3

left by Laurent at 4/12/2010 12:09 AM Gravatar
Hey Bob,

Sorry for the super long delay in answering. I have been head down in projects and presentations since MIX.

Regarding the number of VMs: In my opinion, it is a matter of how you structure your application. If your UI is complex, you can split it in multiple, smaller user controls, each with a VM. I think that the pattern itself scales well. After a certain point (maybe 4 or 5 VMs, maybe even earlier), I would start using an IOC container to manage the VMs. I personally like Unity because it is small and simple to use. If you use Unity, we could argue that the VMLocator is not really needed anymore, but I like to have this object as a global resource, especially when I work in Blend. This makes things easier regarding design time data.

Hopefully this helps. I am currently not 100% happy with the ViewModelLocator implementation, and looking in improving it in V4. In the mean time, I would use an IOC container to manage the VMs.

Cheers,
Laurent

# re: What’s new in MVVM Light V3

left by Stefan de Vogelaere at 4/15/2010 12:18 AM Gravatar
Laurent,
I understand that you want the VMLocator in your global resources; but what if you want to use MEF and have different XAP's to deal with. How would one be able to get design time support for these (external) projects? These do not contain an app.xaml. Thanks.

# re: What’s new in MVVM Light V3

left by Laurent at 4/18/2010 7:31 AM Gravatar
Hi,

You can add an instance of the ViewModelLocator to the Window (or Page) resources.

In fact, you can have multiple instances of the ViewModelLocator, since the setup is made in a static manner. The various instances of VML will all refer to the same ViewModels.

Something like:

<UserControl x:Class="MvvmLight1.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:vm="clr-namespace:MvvmLight1.ViewModel"
mc:Ignorable="d"
Height="300"
Width="300">

<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>

<vm:ViewModelLocator x:Key="Locator" />
</ResourceDictionary>
</UserControl.Resources>

<UserControl.DataContext>
<Binding Source="{StaticResource Locator}" Path="Main" />
</UserControl.DataContext>

<Grid x:Name="LayoutRoot">

<TextBlock FontSize="36"
FontWeight="Bold"
Foreground="Purple"
Text="{Binding Welcome}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
TextWrapping="Wrap" />

</Grid>
</UserControl>

HTH,
Cheers,
Laurent

# re: What’s new in MVVM Light V3

left by Steve at 6/16/2010 5:27 AM Gravatar
How the hell do you use the Messenger? There are no examples except for very cryptic clues.

# re: What’s new in MVVM Light V3

left by Laurent Bugnion at 6/16/2010 7:26 AM Gravatar
There are multiple ways to find out.

1) The source code is abundantly commented. See http://mvvmlight.codeplex.com

2) The XML documentation is available when you install the latest version of the assemblies. This is picked by Intellisense.

3) This sample uses the Messenger, including messages with callbacks:
http://blog.galasoft.ch/archive/2009/10/18/clean-shutdown-in-silverlight-and-wpf-applications.aspx

More documentation will follow.

Greetings,
Laurent

# re: What’s new in MVVM Light V3

left by Steve at 7/6/2010 4:29 PM Gravatar
Thanks for sending the links...I will study them all and let you know how it works out :)

# re: What’s new in MVVM Light V3

left by Pratz at 7/19/2010 3:31 AM Gravatar
Hi Laurent,

Thanks a ton for the MVVM Light toolkit. Makes it really easy to build and test WPF applications.

I am using the MVVM Light toolkit with WPF (VS2010). Is it posible to use .NET RIA Services to implement the service layer? I was quite impressed with what RIA Services did with SL4 and its integration with the Entity Framework, and was wondering if I could use it in a WPF setup. Any thoughts?

Thanks again!

# re: What’s new in MVVM Light V3

left by Bengal cat at 5/25/2011 9:13 AM Gravatar
thanks for sharing news very nice post.

# re: What’s new in MVVM Light V3

left by Binoy at 9/19/2011 4:24 PM Gravatar
If anyone can share some sample apps or code snippet, for getting started with MVVM Lite with Silverlight. Thanks in Advance.

# re: What’s new in MVVM Light V3

left by Haris at 10/6/2011 12:47 PM Gravatar
Hi Laurent. Is there a way to send also the sender and not only EventArgs as a parameter to the RelayCommand? Let me paraphrase that: Can we send multiple parameters to the command?

# re: What’s new in MVVM Light V3

left by Laurent at 10/6/2011 1:29 PM Gravatar
Hi,

Unfortunately the single parameter issue is a limitation of the ICommand interface, on which I have no control. Maybe you can do a binding on a property of the VM that owns the Command (for example bind the SelectedItem of a ListBox) and this way you can get the reference to the item you need.

Cheers
Laurent
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: