Denis Jakus

making tech less cryptic

CTO x Unique People

Denis Jakus

making tech less cryptic

CTO x Unique People

CTO Note

What is MVVM and how to implement it?!3 min read

21 August 2019 .NET
What is MVVM and how to implement it?!3 min read

Hi there! It’s been a while since I wrote my last article due to summertime madness. Little digression, if you are into summertime and jazz, listen to this great jazz performance by Ella Fitzgerald.

What I really needed was some offline time to regenerate and prepare some great new content. So by starting from today, I’ll be back at posting regularly.

Okay, let’s had back to our today’s topic. What is MVVM and how do we implement it?

MVVM in a nutshell

It’s an architectural pattern for implementing user interfaces (UIs) and stands for “Model View ViewModel” (hence capital letters MVVM).

For more on how to implement MVVM in Xamarin apps please read: Part1 and Part2 of building Xamarin apps with Prism.

M or Model

Encapsulates business objects, domain models or data models.

V or View:

Represents something that user sees (page or form).

VM or ViewModel

Is a model specifically tied to a view.
In a nutshell it’s a POCO class with properties which holds everything represented on a view (state, data, methods…)

It really is similar to code behind (if you ask yourself that question) but unlike code behind, is not tightly coupled and is unit testable.

So as you can see, some similarity does exist but fundamentally they are completely different.

When to use MVVM?

Only if you want your application to be unit tested regarding presentation logic and if you are creating a complex application.

How to implement MVVM with C#?

I will show you how to implement MVVM in Xamarin by using C#.
There are 3 ways to implement it.

  1. By writing a bunch of code by yourself (least interesting)
  2. By using Alexandre Chofi BaseViewModel class
  3. *By using Nuget library Fody PropertyChanged

As you might have seen * in 3rd bulletin, this is my favorite type of MVVM implementation, thus far!

Why?
I like simple things, period.

Everything that is providing simplification (without sacrificing any usefulness) I will gladly embrace!

Traditional MVVM by using INotifyPropertyChanged

public class PersonFormViewModel : INotifyPropertyChanged  
    {  
        public event PropertyChangedEventHandler PropertyChanged;  
     
        private string _name;  
        public string Name
        {  
            get  
            {  
                return _name;  
            }  
            set  
            {  
                if (_name!= value)  
                {  
                    _name= value;  
                    NotifyPropertyChanged();  
                }  
            }  
        }  
   
        private int _age;  
        public int Age  
        {  
            get  
            {  
                return _age;  
            }  
            set  
            {  
                if (_age!= value)  
                {  
                    _age= value;  
                    NotifyPropertyChanged();  
                }  
            }  
        }  
		
	protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
        }  
    }  

MVVM by using Alexandre Chofi created base class

public class AlexandreChofiPersonFormViewModel : BaseViewModel  
    {  
        private string _name;  
        public string Name
        {  
            get  
            {  
                return _name;  
            }  
            set  
            {  
                SetProperty(ref _name, value);  
            }  
        }  
   
        private int _age;  
        public int Age  
        {  
            get  
            {  
                return _age;  
            }  
            set  
            {  
                SetProperty(ref _age, value);  
            }  
        }  
    }  

His BaseViewModel class:

public class BaseViewModel : INotifyPropertyChanged  
    {  
        public event PropertyChangedEventHandler PropertyChanged;  
   
        protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)  
        {  
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs((propertyName)));  
        }  
   
        protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)  
        {  
            if (EqualityComparer<T>.Default.Equals(storage, value))  
            {  
                return false;  
            }  
            storage = value;  
            OnPropertyChanged(propertyName);  
   
            return true;  
        }  
    }

MVVM by using Nuget library FodyPropertyChanged (my favorite way of implementing MVVM)

[ImplementPropertyChanged]  
    public class FodyPersonFormViewModel  
    {  
        public string Name { get; set; }  
        public int Age { get; set; }  
    }  

CONCLUSION

I hope you see why the latter is by far my favorite way of implementing MVVM.
You just need to annotate your ViewModel class and voila!

MVVM is really useful but not in all cases (i.e. quick prototyping).
By using some of the above mentioned ways, you could really use it anytime and anywhere though.

Just don’t repeat yourself and use what others already implemented and tested in real case scenarios. So I highly recommend using the 3rd way.

As always, if you have any doubts or questions, don’t hesitate to contact me via any of the listed social networks or email!

Cheers!

Taggs:
Related Posts
How to organize Visual Studio projects

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like In my latest Youtube video,…

Caching in DotNet Core WebAPI using Strategy Pattern

Facebook Twitter Evernote Hacker News Gmail Print Friendly Yahoo Mail reddit LinkedIn Blogger Tumblr Like Let me write today about…

Write a comment