Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

Using EventToCommand Behavior in MVVM ViewModel in Xamarin


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

Behavior-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.

  1. Method Execute
  2. Method CanExecute
  3. 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.

ai-Hiring-banner

Fig: Create a Xamarin project

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

ai-Hiring-banner

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.

Behavior-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.

  1. Method Execute
  2. Method CanExecute
  3. 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.

ai-Hiring-banner

Fig: Create a Xamarin project

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

ai-Hiring-banner

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.