EventToCommand is now built into Windows 8.1!

Tags: Windows 8.1, MVVM

In MVVM code is separated to make it easier to test. You write a View Model and bind it to the View. Sometimes the View has elements that trigger events that you want to listen for in the View Model. This is where EventToCommand comes in handy. However, up till now this has been a bit of a trick to do in Windows 8 because it isn't built in. You have to use a third party extension or write all the wiring up yourself.

Until now. Windows 8.1 is coming to the rescue. Blend for Visual Studio 2013 includes behaviors such as EventTriggerBehavior to satisfy your InvokeCommandAction needs. I'm ashamed to say though that I'm not one to hit the old "Edit in Blend" link in Visual Studio. I prefer to do all the hard work by hand. Well here's how you can do it by hand.

The first step is to add a reference to the Windows SDK item BehaviorsXamlSDKManaged in the project. I had to unload the project and edit the csproj file directly to get this in since it didn't show on the "Add Reference…" dialog.

 <ItemGroup>
<!-- A reference to the entire .Net Framework and Windows SDK are automatically included --> 
<SDKReference Include="BehaviorsXamlSDKManaged, Version=12.0" /> 
</ItemGroup> 

Next we need to add some new XML namespaces to our XAML page:

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

Here I'm using the same names that Blend gives them. I'm sure you can rename them to make them clearer. Particularly Core.

Then you set the hooks in the XAML code. In this example I have a Button that I'm listening for the "PointerExited" event and sending in the item as a command parameter:

<Interactivity:Interaction.Behaviors>
  <Core:EventTriggerBehavior EventName="PointerExited">
    <Core:InvokeCommandAction Command="{Binding OnPointerExited}" CommandParameter="{Binding}" />
  </Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>

Finally you hook this into your ViewModel using the same DelegateCommand infrastructure you would use for any other command.

I know this is a brief overview, and if you'd like a full example please look me up on Twitter (@spatacoli) and ask for a full demo.

Add a Comment