by Wojciech Sura

Event-to-command in Windows Phone

During writing my Windows Phone application I ran into a problem: I wanted the button to behave differently, depending on whether user tapped it or pressed-and-held.

Most XAML controls provide a Holding event, which occurs when user keeps touching an item – so the solution seems to be as simple as implementing an event.

But that doesn’t look nice in XAML – most actions can be implemented declaratively – as bindings to commands in the viewmodel. Implementation of event in code-behind seems like a code smell in this beautiful MVVM environment.

There’s a solution though – to use Behaviors SDK.

First of all, add Behaviors SDK (XAML) to your project references – you may find it among few assemblies, which Microsoft provides as optional ones for Windows Phone applications.

Then – as usual – you’ll have to define XML namespaces for two additional C# namespaces:

[xml]<Page

xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:icore="using:Microsoft.Xaml.Interactions.Core">[/xml]

Finally, you may add a behavior and action to the button:

[xml]<Button Command="{Binding TapCommand}">
<i:Interaction.Behaviors>
<icore:EventTriggerBehavior EventName="Holding">
<icore:InvokeCommandAction Command="{Binding HoldingCommand}" />
</icore:EventTriggerBehavior>
</i:Interaction.Behaviors>
Press or hold me
</Button>[/xml]

Remember though, that after HoldingCommand, the TapCommand will fire as well. Make sure to implement it properly.