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.