Bulb Flash:- Some practical WPF MVVMLight tips!

One of our major projects recently used WPF 4.0 with MVVM pattern.We used the MVVM Light Toolkit for implementing the MVVM Pattern.

The MVVM Light Toolkit definitely has a lot to offer to make your life easier but the documentation is not exemplary!

Few things we learnt down the road as we came to a close on the project are

1. You are better off using the ViewModalLocator. We didn’t use it initially and realized that our ViewModels are not getting Disposed, multiple view models are getting created especially when using the “Commanding” feature!

2. When using Commands , if you are not using the ViewModalLocator, try not to set the IsDataSource property as it will change the DataContext of your screen to the new ViewModel and there will be inconsistency during commanding as previously set variables will not be available in the new VM. Or if you do need to set the IsDataSource property send all data needed by the command handler as arguments( because previously set data will not be available to the new VM)

3. You need a default empty constructor in all your ViewModels or your XAML screens commands won’t work(They instantiate the empty construtor)

4. You can pass event args parameters in commands using PassEventArgsToCommand="True" in your EventToCommand XAML

5. When using messaging use the method overload Send<TMessage>(TMessage message, object token).Using the token to register and send messages ensures it is delivered only to valid subscribers!

6. Every time you register for an event using the Messenger.Default.Register….ensure you Unregister also using the Messenger.Default.Unregister or else you might have memory leaks!!

Will try to write more elaborate posts detailing out these and more issues .Meanwhile drop a note at anshulee@cennest.com if you have any queries/ need more tips related to MVVM…

Until then!

Cennest!

Commanding within DataTemplates in MVVM!

A quick post about setting commands within DataTemplates when using the MVVM pattern!

When you are inside a DataTemplate the DataContext is changed to the  the current item, so to access the command you will need to use the “relative source”

Something like

 <Button Content="Delete" Width="Auto" 
Command="{Binding DataContext.RemoveCommand, 
RelativeSource={RelativeSource FindAncestor,
 AncestorType={x:Type ItemsControl}}}" 
CommandParameter="{Binding}">

Hope this real quick note helps save you some time!!

Until next time!

Cennest!