Things I Think Are Cool: Event to Command Behavior
Things I Think Are Cool is a blog series where I talk about things I have found interesting and helpful. They can be time savers, productivity tools, podcasts, books, products, or even people.
If you're using the MVVM pattern in Xamarin.Forms, then most likely you're using Commands to bind events from the user interface to actions in the view model.
There are a couple of annoyances with Commands, as setup in Xamarin.Forms. One is that there is only one Command per control. Thus only one event per control can be bound to an action in the view model.
Another is there are controls which do not have a Command defined at them at all! (I'm looking at you ListView
.)
However, there is a pattern ... with all the code provided ... that alleviates both of those pain points. The Event to Command Behavior.
Why It's Cool
The Event to Command Behavior is a Xamarin.Forms Behavior that is designed to associate controls that were not designed with Commands in mind.
In other words - it allows you to map any arbitrary event on a control to a Command ... even the ItemSelected
event on a ListView
!!
A Behavior is a class that modifies the behavior of Xamarin.Forms control without having to subclass or write anything in the code-behind.
(The simple example being one that validates numbers on an Entry
control.)
A Behavior works by having a function get invoked whenever it is added to a control OnAttachedTo
- and the instance of whatever control the Behavior is being added to is passed as a parameter.
Thus it's possible to handle certain events on the control - and with the power of the BindableProperty
- bind a Command to any event!
How Do I Get It?
There is great documentation on the Event to Command Behavior and how it works on a very detailed level on Xamarin's site.
If you want to cut straight to the chase and get the code, here you go.