Taoffi's blog

prisonniers du temps

Xamarin forms: avoid using string constants in NotifyPropertyChanged

 

As you know, notifying property changes is an essential pattern for Bindings to work as expected on xaml UI controls. Solution objects that are related to the UI (at least those of the 'VM' in: MV[VM]) should implement the INotifyPropertyChanged Interface. That is: expose a PropertyChanged event (of Type PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e)).

Property changes consequently raise this event for any subscriber to be notified of the change.

The PropertyChangedEventArgs sent to the subscriber contains the changed property name.

So, for instance, if you change a property named BirthDate:

public DateTime BirthDate
{
    get { return _birthdate; }
    set
    {
        _birthdate = value;
        OnPropertyChanged("BrirthDate");
    }
}

One known issue is that when you change the property name, you may forget changing the name used in the change notification. And that, of course, produces unexpected behaviors that may be difficult to track.

A solution I use to avoid this (don't remember where I did found it!), is using System.Linq.Expressions to write something similar to this:

 

// Note: TProperty is the calling property Type 
protected void NotifyPropertyChanged<TProperty>(Expression<Func<TProperty>> property) 
{
    var expression     = property.Body as MemberExpression; 
    if (expression == null || expression.Member == null) 
        return; 
    string name        = expression.Member.Name;

    OnPropertyChanged(name); 
}

And that would allow us to avoid using string constants for property names… like in:

 

public DateTime BirthDate
{
    get { return _birthdate; }
    set
    {
        _birthdate = value;
        NotifyPropertyChanged(() => BrirthDate);
    }
}

 

 

Comments are closed