Invoking Commands from Events in WinRT

February 21st 2015 MvvmLight Windows Store

Slight differences between XAML platforms can quickly throw you off track when switching between them. While I was recently writing my first WinRT application for Windows Phone 8.1 I spent more time than I should have, looking for a way to invoke a command on the view model from an event. Due to the changing nature of WinRT and Windows Phone platforms, it's difficult to find up-to-date information on the topic, therefore I'm writing this blog post as a future reference for myself.

On most platforms MvvmLight includes a helper class to make that work, so the most common advice you'll find, will be to use that. In WinRT the class is suspiciously missing. Not only that; at first sight there is no Interactivity namespace either. Fortunately, that's not true; since Windows (Phone) 8.1 it is in fact included in the Behaviors SDK extension which you can reference from your project. In that same extension the replacement for the missing EventToCommand trigger is available as well: it's called InvokeCommandAction.

Taking all that into account, triggering commands from events actually becomes pretty easy:

  • Add reference to Behaviors SDK (XAML) extension from your project via Reference Manager dialog:

Behaviors SDK (XAML) in Reference Manager

  • Add the Microsoft.Xaml.Interactivity namespaces at the top of the page:
<Page xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
  • Use InvokeCommandAction in your page to invoke the command when an event is triggered:
    <core:EventTriggerBehavior EventName="Loaded">
        <core:InvokeCommandAction Command="{Binding ActivateCommand}" />

That's it: when this page loads, it will invoke ActivateCommand in its DataContext.

Creative Commons License