Using XAML Behaviours to stop MVVM Light Messenger Action Executing Multiple Times

In MVVM Light, when we derive our ViewModel from ViewModelBase, we inherit a Cleanup() method.

This method can be overridden, by default it will unregister all messages for the ViewModel, so calling Cleanup() on our view model will prevent multiple subscriptions occurring if we navigate back to the ViewModel and register it again.

But where do we call Cleanup() ?

One method is to get the View to call the ViewModel’s Cleanup() method when it is unloaded.

We could write a codebehind “shim” to cast the View’s DataContext to our ViewModel type then call its Cleanup() method.

Another method is to use the Behaviours SDK (XAML).

image

Once we add this reference we can add some namespaces in our View XAML:

xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"

Now in our page, we can add the following XAML:

<interactivity:Interaction.Behaviors>
    <core:EventTriggerBehavior EventName="Unloaded">
        <core:CallMethodAction TargetObject="{Binding}" MethodName="Cleanup" />
    </core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>

Now every time the Page’s Unloaded event is raised, the Cleanup() method will be called on our ViewModel, which will unregister all messages for the bound ViewModel.

Add comment

Loading