×

iFour Logo

Using EventToCommand Behavior in MVVM ViewModel in Xamarin

Kapil Panchal - December 04, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Using EventToCommand Behavior in MVVM ViewModel in Xamarin

Xamarin forms behaviors are created by deriving from Behavior or Behavior class and the behavior can enable you to implement code that you have to write as code-behind because it can directly interact with the API of the control. Attached behavior is a static class with one or more attached properties.

For using EventToCommand behavior you must set the below behavior properties.

EventName: Give the appropriate name of the event that the behavior can listen to (Ex: LoginEvent).

Command: The ICommand interface is a part of the .NET Framework and the ICommand interface used a lot in MVVM structure. Using the command interface, we can acquire a clean workflow of the application. The ICommand interface has three members.

  • Method Execute

  • Method CanExecute

  • CanExecuteChanged event

Now, let’s see how Command behavior can work in Xamarin Forms.

Step: 1

Initially open visual studio 2017 and create a new Xamarin projects.

Create a Xamarin project

Fig: Create a Xamarin project

After selecting Xamarin forms, give it appropriate name and select Blank App for Android and iOS.

Select the template and platform

Fig: Select the template and platform

Step: 2

Now, create a main Behavior class that can be derived from Behavior and BindableObject.

MainBehaviorClass.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Text;
using Xamarin.Forms;

namespaceEventToCommand
{
publicclassMainBehaviorClass : Behaviorwhere T : BindableObject
  {
  private T _behaviorObject{ get; set; }
  protectedoverridevoidOnAttachedTo(T Attachbindable)
      {
      base.OnAttachedTo(Attachbindable);
        _behaviorObject = Attachbindable;

        if(Attachbindable.BindingContext != null)
        {
          BindingContext = Attachbindable.BindingContext;
        }

        Attachbindable.BindingContextChanged += OnBindingContextChanged;
      }

      protectedoverridevoidOnDetachingFrom(T Detachingbindable)
    {
      base.OnDetachingFrom(Detachingbindable);
      Detachingbindable.BindingContextChanged -= OnBindingContextChanged;
      _behaviorObject = null;
    }

    voidOnBindingContextChanged(object sender, EventArgs e)
    {
      OnBindingContextChanged();
    }

    protectedoverridevoidOnBindingContextChanged()
    {
      base.OnBindingContextChanged();
      BindingContext = _behaviorObject.BindingContext;
    }
  }
}
      

OnAttachedTo method can be used to perform any setup actions.

OnDetachingFrom method can be used to perform clean up. The behavior is removed from the UI control when the OnDetachingFrom method is fired.

<

Step: 3

After creating MainBehaviorClass, create an EventToCommand Behavior Class to convert your events to command and also implement bindable properties.

EventToCommandBehaviorClass.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Reflection;
usingSystem.Text;
usingSystem.Windows.Input;
using Xamarin.Forms;

namespaceEventToCommand
{
publicclassEventToCommandBehaviorClass :MainBehaviorClass
  {
      Delegate GetDelegate;
  publicstaticreadonlyBindablePropertyNameofEvent = BindableProperty.Create("NameofEvent", typeof(string), typeof(EventToCommandBehaviorClass), null, propertyChanged: OnEventName);

  privatestaticvoidOnEventName(BindableObjectbindable, objectoldEventValue, objectnewEventValue)
      {
  var behavior = (EventToCommandBehaviorClass)bindable;

  if (behavior.behaviorObject == null)
          {
      return;
          }

    stringoldName = (string)oldEventValue;
    stringnewName = (string)newEventValue;

    behavior.DeregisteredEvent(oldName);
    behavior.RegisteredEvent(newName);
      }

  publicstaticreadonlyBindablePropertypropertyofCommand = BindableProperty.Create("Command", typeof(ICommand), typeof(EventToCommandBehaviorClass), null);

  publicstringEventNameProperty
      {
    get
          {
      return (string)GetValue(NameofEvent);
          }
    set
          {
      SetValue(NameofEvent, value);
          }
      }
  publicICommand Command
      {
    get{ return (ICommand)GetValue(propertyofCommand); }
    set{ SetValue(propertyofCommand, value); }
      }

  protectedoverridevoidOnAttachedTo(VisualElementAttachbindable)
      {
    base.OnAttachedTo(Attachbindable);
    RegisteredEvent(EventNameProperty);
      }

  protectedoverridevoidOnDetachingFrom(VisualElementDetachingbindable)
      {
    DeregisteredEvent(EventNameProperty);
    base.OnDetachingFrom(Detachingbindable);
      }

  voidRegisteredEvent(string name)
      {
    if (string.IsNullOrWhiteSpace(name))
          {
      return;
          }
  EventInfo events = behaviorObject.GetType().GetRuntimeEvent(name);

  if(events == null)
          {
      thrownewArgumentException("Expected Event not register");
          }

    MethodInfo info = typeof(EventToCommandBehaviorClass).GetTypeInfo().GetDeclaredMethod("OnEvent");
    GetDelegate = info.CreateDelegate(events.EventHandlerType, this);
    events.AddEventHandler(behaviorObject, GetDelegate);
      }

  voidDeregisteredEvent(string name)
      {
    if(string.IsNullOrWhiteSpace(name) || GetDelegate == null)
          {
      return;
          }
    EventInfoeventInfo = GetDelegate.GetType().GetRuntimeEvent(name);

    if(eventInfo == null)
    {
        thrownewArgumentException("Expected Event de-register");
    }

    eventInfo.RemoveEventHandler(behaviorObject, GetDelegate);
    GetDelegate = null;
  }

voidOnEvent(object sender, objecteventArgs)
    {
  if(Command == null)
  {
        return;
  }
    object parameter;

    parameter = eventArgs;

  if (Command.CanExecute(parameter))
  {
    Command.Execute(parameter);
  }
  }
}
}

      

Step: 4

Now, we will create a model for the reusable purpose. Here, we can use the Refresh command and CleanUp command. We can use the Refresh command with the page load time and the CleanUp command works when your page’s disappearing time.

CommandModel.cs

usingGalaSoft.MvvmLight;
using System;
usingSystem.Collections.Generic;
usingSystem.Text;
using Xamarin.Forms;

namespaceEventToCommand
{
publicclassCommandModel :ViewModelBase
  {
private Command _refreshCommand;
private Command _cleanUpCommand;

public Command RefreshCommand
      {
  get
    {
      return _refreshCommand ?? (_refreshCommand = new Command(this.RefreshPage));
          }
      }

publicvirtualvoidRefreshPage()
      {

      }

public Command CleanUpCommand
      {
  get
    {
      return _cleanUpCommand ?? (_cleanUpCommand = new Command(this.CleanUpPage));
          }
      }

  publicvirtualvoidCleanUpPage()
      {
    base.Cleanup();
      }
  }
}
      

Planning to Hire Xamarin App Development Company? Your Search ends here.

Step: 5

Create a model, here Employee is our model name. In this model, we can add the Employee name, id, and designation.

Employee.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Text;

namespaceEventToCommand
{
publicclassEmployee
  {
  publicintIdofEmployee{ get; set; }
  publicstringNameofEmployee{ get; set; }
  publicstringDesignationofEmployee{ get; set; }
  }
}
      

After creating a model, create a one ViewModel, in this ViewModel we can use the CleanUp command and Refresh command from the CommandModel on your page. In this ViewModel, we can inherit the CommandModel class.

MainViewModel.cs

using System;
usingSystem.Collections.Generic;
usingSystem.Collections.ObjectModel;
usingSystem.Text;

namespaceEventToCommand
{
publicclassMainViewModel :CommandModel
  {
  publicMainViewModel()
      {

      }

  privateObservableCollection _employee;

  publicObservableCollection employees
      {
    get
          {
      return _employee;
          }
    set
          {
      Set(() => employees, ref _employee, value);
          }
      }

  publicoverridevoidRefreshPage()
      {
    base.RefreshPage();

    this.employees = newObservableCollection();
    this.employees.Add(new Employee { IdofEmployee = 101, NameofEmployee = "John", DesignationofEmployee = "HR" });
    this.employees.Add(new Employee { IdofEmployee = 102, NameofEmployee = "Jack", DesignationofEmployee = "Marketing" });
    this.employees.Add(new Employee { IdofEmployee = 103, NameofEmployee = "Mickel", DesignationofEmployee = "Tester" });
    this.employees.Add(new Employee { IdofEmployee = 104, NameofEmployee = "Smith", DesignationofEmployee = "BA" });
      }

  publicoverridevoidCleanUpPage()
      {
    this.employees = null;
    base.CleanUpPage();
      }
  }
}
      

Step: 7

Now, here we can implement EventToCommandBehaviorClass in the view.

MainPage.xaml













      

Conclusion


As you can see, an EventToCommand behavior can be used to bind any event on a visual element to an ICommand, and typically, this element is used in XAML to connect the attached element to a command.

Using EventToCommand Behavior in MVVM ViewModel in Xamarin Xamarin forms behaviors are created by deriving from Behavior or Behavior class and the behavior can enable you to implement code that you have to write as code-behind because it can directly interact with the API of the control. Attached behavior is a static class with one or more attached properties. For using EventToCommand behavior you must set the below behavior properties. EventName: Give the appropriate name of the event that the behavior can listen to (Ex: LoginEvent). Command: The ICommand interface is a part of the .NET Framework and the ICommand interface used a lot in MVVM structure. Using the command interface, we can acquire a clean workflow of the application. The ICommand interface has three members. Method Execute Method CanExecute CanExecuteChanged event Now, let’s see how Command behavior can work in Xamarin Forms. Step: 1 Initially open visual studio 2017 and create a new Xamarin projects. Fig: Create a Xamarin project After selecting Xamarin forms, give it appropriate name and select Blank App for Android and iOS. Fig: Select the template and platform Step: 2 Now, create a main Behavior class that can be derived from Behavior and BindableObject. MainBehaviorClass.cs using System; usingSystem.Collections.Generic; usingSystem.Text; using Xamarin.Forms; namespaceEventToCommand { publicclassMainBehaviorClass : Behaviorwhere T : BindableObject { private T _behaviorObject{ get; set; } protectedoverridevoidOnAttachedTo(T Attachbindable) { base.OnAttachedTo(Attachbindable); _behaviorObject = Attachbindable; if(Attachbindable.BindingContext != null) { BindingContext = Attachbindable.BindingContext; } Attachbindable.BindingContextChanged += OnBindingContextChanged; } protectedoverridevoidOnDetachingFrom(T Detachingbindable) { base.OnDetachingFrom(Detachingbindable); Detachingbindable.BindingContextChanged -= OnBindingContextChanged; _behaviorObject = null; } voidOnBindingContextChanged(object sender, EventArgs e) { OnBindingContextChanged(); } protectedoverridevoidOnBindingContextChanged() { base.OnBindingContextChanged(); BindingContext = _behaviorObject.BindingContext; } } } OnAttachedTo method can be used to perform any setup actions. OnDetachingFrom method can be used to perform clean up. The behavior is removed from the UI control when the OnDetachingFrom method is fired. < Read More: USEFUL PLUGINS IN XAMARIN Step: 3 After creating MainBehaviorClass, create an EventToCommand Behavior Class to convert your events to command and also implement bindable properties. EventToCommandBehaviorClass.cs using System; usingSystem.Collections.Generic; usingSystem.Reflection; usingSystem.Text; usingSystem.Windows.Input; using Xamarin.Forms; namespaceEventToCommand { publicclassEventToCommandBehaviorClass :MainBehaviorClass { Delegate GetDelegate; publicstaticreadonlyBindablePropertyNameofEvent = BindableProperty.Create("NameofEvent", typeof(string), typeof(EventToCommandBehaviorClass), null, propertyChanged: OnEventName); privatestaticvoidOnEventName(BindableObjectbindable, objectoldEventValue, objectnewEventValue) { var behavior = (EventToCommandBehaviorClass)bindable; if (behavior.behaviorObject == null) { return; } stringoldName = (string)oldEventValue; stringnewName = (string)newEventValue; behavior.DeregisteredEvent(oldName); behavior.RegisteredEvent(newName); } publicstaticreadonlyBindablePropertypropertyofCommand = BindableProperty.Create("Command", typeof(ICommand), typeof(EventToCommandBehaviorClass), null); publicstringEventNameProperty { get { return (string)GetValue(NameofEvent); } set { SetValue(NameofEvent, value); } } publicICommand Command { get{ return (ICommand)GetValue(propertyofCommand); } set{ SetValue(propertyofCommand, value); } } protectedoverridevoidOnAttachedTo(VisualElementAttachbindable) { base.OnAttachedTo(Attachbindable); RegisteredEvent(EventNameProperty); } protectedoverridevoidOnDetachingFrom(VisualElementDetachingbindable) { DeregisteredEvent(EventNameProperty); base.OnDetachingFrom(Detachingbindable); } voidRegisteredEvent(string name) { if (string.IsNullOrWhiteSpace(name)) { return; } EventInfo events = behaviorObject.GetType().GetRuntimeEvent(name); if(events == null) { thrownewArgumentException("Expected Event not register"); } MethodInfo info = typeof(EventToCommandBehaviorClass).GetTypeInfo().GetDeclaredMethod("OnEvent"); GetDelegate = info.CreateDelegate(events.EventHandlerType, this); events.AddEventHandler(behaviorObject, GetDelegate); } voidDeregisteredEvent(string name) { if(string.IsNullOrWhiteSpace(name) || GetDelegate == null) { return; } EventInfoeventInfo = GetDelegate.GetType().GetRuntimeEvent(name); if(eventInfo == null) { thrownewArgumentException("Expected Event de-register"); } eventInfo.RemoveEventHandler(behaviorObject, GetDelegate); GetDelegate = null; } voidOnEvent(object sender, objecteventArgs) { if(Command == null) { return; } object parameter; parameter = eventArgs; if (Command.CanExecute(parameter)) { Command.Execute(parameter); } } } } Step: 4 Now, we will create a model for the reusable purpose. Here, we can use the Refresh command and CleanUp command. We can use the Refresh command with the page load time and the CleanUp command works when your page’s disappearing time. CommandModel.cs usingGalaSoft.MvvmLight; using System; usingSystem.Collections.Generic; usingSystem.Text; using Xamarin.Forms; namespaceEventToCommand { publicclassCommandModel :ViewModelBase { private Command _refreshCommand; private Command _cleanUpCommand; public Command RefreshCommand { get { return _refreshCommand ?? (_refreshCommand = new Command(this.RefreshPage)); } } publicvirtualvoidRefreshPage() { } public Command CleanUpCommand { get { return _cleanUpCommand ?? (_cleanUpCommand = new Command(this.CleanUpPage)); } } publicvirtualvoidCleanUpPage() { base.Cleanup(); } } } Planning to Hire Xamarin App Development Company? Your Search ends here. See here Step: 5 Create a model, here Employee is our model name. In this model, we can add the Employee name, id, and designation. Employee.cs using System; usingSystem.Collections.Generic; usingSystem.Text; namespaceEventToCommand { publicclassEmployee { publicintIdofEmployee{ get; set; } publicstringNameofEmployee{ get; set; } publicstringDesignationofEmployee{ get; set; } } } After creating a model, create a one ViewModel, in this ViewModel we can use the CleanUp command and Refresh command from the CommandModel on your page. In this ViewModel, we can inherit the CommandModel class. MainViewModel.cs using System; usingSystem.Collections.Generic; usingSystem.Collections.ObjectModel; usingSystem.Text; namespaceEventToCommand { publicclassMainViewModel :CommandModel { publicMainViewModel() { } privateObservableCollection _employee; publicObservableCollection employees { get { return _employee; } set { Set(() => employees, ref _employee, value); } } publicoverridevoidRefreshPage() { base.RefreshPage(); this.employees = newObservableCollection(); this.employees.Add(new Employee { IdofEmployee = 101, NameofEmployee = "John", DesignationofEmployee = "HR" }); this.employees.Add(new Employee { IdofEmployee = 102, NameofEmployee = "Jack", DesignationofEmployee = "Marketing" }); this.employees.Add(new Employee { IdofEmployee = 103, NameofEmployee = "Mickel", DesignationofEmployee = "Tester" }); this.employees.Add(new Employee { IdofEmployee = 104, NameofEmployee = "Smith", DesignationofEmployee = "BA" }); } publicoverridevoidCleanUpPage() { this.employees = null; base.CleanUpPage(); } } } Step: 7 Now, here we can implement EventToCommandBehaviorClass in the view. MainPage.xaml Conclusion As you can see, an EventToCommand behavior can be used to bind any event on a visual element to an ICommand, and typically, this element is used in XAML to connect the attached element to a command.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
Power Apps Solving 13 Legal Challenges
Power Apps Solving 13 Legal Challenges

There is a common misconception that bringing technology into the legal field won't be effective as this profession relies heavily on evidence and facts. However, if you look at it...

How to Automate Power BI Reports Using Power Automate
How to Automate Power BI Reports Using Power Automate

"Does Power Automate work with Power BI?”. If you think the same, you’re at the right place. Manual reporting plays an important role in business decision-making but requires more...

What’s New in .NET 9?
What’s New in .NET 9?

Today, we’re thrilled to present you with the first glimpse of .NET 9 release and let you know what features and updates you can anticipate in this new version. Various professionals believe that it’s the right time to explore and adopt the latest version of .NET for your upcoming projects. It is even recommended for projects built using .NET 6 or .NET 8, due to the framework updates made in this version.