Phillip Trelford's Array

POKE 36879,255

C# 5 CallerMemberName from Silverlight & WPF 4.0

C# 5 allows you to obtain the method or property of the caller to a method using the CallerMemberName attribute under System.Runtime.CompilerServices in .Net 4.5:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class ObservableObject : INotifyPropertyChanged 
{
  protected void NotifyPropertyChanged([CallerMemberName] string name = null)
  {
    var e = PropertyChanged;
    if (e != null) e(this, new PropertyChangedEventArgs(name));
  }

  public event PropertyChangedEventHandler PropertyChanged;
}

This is particularly useful in XAML applications using WPF, Silverlight or WinRT that signal changes to properties via the INotifyPropertyChanged interface. With the new feature you don’t need to explicitly specify a literal string or lambda expression when notifying that a property has changed from it’s setter:

public class ViewModel : ObservableObject
{
  private object _value;

  public object Value
  {
    get { return _value; }
    set
    {
      _value = value;
      this.NotifyPropertyChanged();
    }
  }
}

Silverlight and earlier versions of the .Net Framework behind WPF do not have the CallerMemberName attribute. The good news is that you simply need to define it in yourself and assuming you’re using the C# 5 compiler then it just works:

namespace System.Runtime.CompilerServices
{
  /// <summary>
  /// Allows you to obtain the method or property name of the caller.
  /// </summary>
  [AttributeUsageAttribute(AttributeTargets.Parameter, Inherited = false)]
  public sealed class CallerMemberNameAttribute : Attribute { }
}

Pingbacks and trackbacks (1)+

Comments are closed