×
iFour Logo

Using EventToCommand Behavior in MVVM ViewModel in Xamarin

iFour Team - December 04, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

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.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Is Java Still in Demand in 2023?
Is Java Still in Demand in 2023?

Table of Content 1.Factors that ensure Java’s continued dominance 1.1.The use case for Java 1.2.Java has a Vast ecosystem. 1.3.Java is both efficient and widely...

Key factors to consider before choosing Customized or Off-the-shelf software
Key factors to consider before choosing Customized or Off-the-shelf software

Table of Content 1.What is COTS? 2.What are the advantages of Off-the-shelf software development? 3.What are the advantages of Custom software development? 4.Customized...

Off-the-shelf vs custom software development: Choosing the best for business success.
Off-the-shelf vs custom software development: Choosing the best for business success.

Table of Content 1.What is Custom software development? 2.What is Off-the-shore software development? 3.How to choose the best software for business? 4.Off-the-shelf...