Delpin Susai Raj Thursday, 28 November 2019

Xamarin.Forms - EventToCommand Behavior in MVVM ViewModel

In this blog post, you will learn how to use Appearing and Disappearing in MVVM ViewModel using EventToCommand Behaviour in Xamarin.Forms.


Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

EventToCommand Behaviour

EventToCommandBehavior class is a reusable Xamarin.Forms custom behavior that executes a command in response to any event firing.

Following behavior properties must be set to use the EventToCommand behavior:
  1. EventName – the name of the event the behavior listens to(Ex: Apperaing).
  2. Command – the ICommand to be executed. The behavior expects to find the ICommand instance on the BindingContext of the attached control, which may be inherited from a parent element.
  • Visual Studio 2017 or later (Windows or Mac)
Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform.
Create BehaviourBase Class 

Now, Create a Behaviour Base class Derived from Behavior and BindableObject


Create EventToCommand Behaviour

Here, Create a EventToCommand Behaviour Class to convert your events to Commad and also implement bindable properties.
  1. EventName
  2. Command


In this step, I Create a common BaseViewModel for reusable purpose.

Note: I use RelayCommand Instead of Command. you can use Command.


Refresh command indicate to Appearing Commad. Whatever you want to implement when page load time you can use RefrehCommad.


Cleanup command indicate to OnDisapearing. This CleanUpCommand when your page is dis appearing time it will be called.



Now, Use Refresh and CleanUp command from BaseViewMmodel in your Pages.


Setting up the User Interface

Here, Implement EventToCommandBehaviour in your View.

Add Namespace

Add Behaviour


Click the "Play" button to try it out.

I hope you have understood how to use Appearing and Disappearing in MVVM ViewModel using EventToCommand Behaviour in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. Happy Coding :)

No comments:

Post a Comment