Pages - Menu

Thursday, April 6, 2017

INotifyPropertyChange without boilerplate code in Xamarin.Forms

Implementing INotifyPropertyChange is pretty straightforward. Usually, you create a base ViewModel class which implements it and which usually contains RaisePropertyChanged method:

public abstract class BaseViewModel : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(
        [CallerMemberNamestring propertyName = "")
    {
        PropertyChanged?.Invoke(thisnew PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

Now you can extend the BaseViewModel and use it this way:
public class UserViewModel : BaseViewModel
{
    private string login;
    public string Login
    {
        get
        {
            return login;
        }
        set
        {
            if (login == value)
                return;

            login = value;
            RaisePropertyChanged();
        }
    }

    private string password;
    public string Password
    {
        get
        {
            return password;
        }
        set
        {
            if (password == value)
                return;

            password = value;
            RaisePropertyChanged();
        }
    }
}

For very small applications it can be a good enough approach, however, in bigger applications it turns into a lot of boring boilerplate code. Here is where NotifyPropertyChanged.Fody comes into play! With this nice package our code will turn into:

[ImplementPropertyChanged]
public abstract class BaseViewModel {}

public class UserViewModel : BaseViewModel
{
    public string Login { getset; }
    public string Password { getset; }
}

Easy as it is! I highly recommend to get familiar with the documentation as it contains a lot of useful information about more advanced flows. For example, if you need to RaisePropertyChange for dependent properties or to skip equality comparison.

No comments:

Post a Comment