EventToCommand in Xamarin Forms Apps

This component is a part of Pillar, a lightweight MVVM framework that I made for Xamarin.Forms 1.x and 2.x. Please check it out on Nuget or GitHub.

An EventToCommand behavior can be used to bind any event on a visual element to an ICommand. Typically, this element is used in XAML to connect the attached element to a command located in a ViewModel.

When I started playing with Xamarin Forms, I found myself in a situation where I had to bind the ItemTapped event of the ListView to a command. I managed to do so by using the Behaviors from the Cavalli Corrado’s nuget package.

But since Xamarin Forms officially supports Behavior in version 1.3, I wanted to write my own.

EventToCommand Behavior usage

Here is an example of how I can bind the ItemTapped event of the ListView to a Command which takes as parameter the BindingContext of the tapped item, using my EventToCommand.

The ListView ViewModel has a “SayHelloCommand”:

I need a converter to extract the tapped BindingContext from the ItemTappedEventArgs :

And finally, here is the View :

How it’s done

Where BindableBehavior is a BindingContext-aware Behavior , made by Jonathan Yates :

As you can see, the EventToCommandBehavior can use an EventArgsConverter which is an IValueConverter.
It is very useful in some cases, for example when you need to pass an argument taken from an EventArgs to the Command.

6 thoughts on “EventToCommand in Xamarin Forms Apps”

  1. Anthony, thank you very much for sharing your snippet here. I had tried using Corcav.Behaviors, but had problems getting it working on Xamarin Form 2.0 with UWP. I am successfully using your approach to implement EventToCommand Behaviors with Forms 2.0 on a Universal Windows Platform app!

    This is a nice contribution and I look forward to any additions you might make.

  2. This doesn’t work for me. The event wiring all works, but the ICommand Command object in the behavior class is always null when the event fires. It looks like the Command=”{Binding BlahDeBlah}” in the XAML is just not binding. Setting a breakpoint on the setter of the Behavior Command property confirms this, as it is never hit. I have tried both ItemSelected and ItemTapped events, and both give same symptoms.

Leave a Reply