Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Without using something like postsharp, the minimal version I use uses something like:</p> <pre><code>public class Data : INotifyPropertyChanged { // boiler-plate public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } protected bool SetField&lt;T&gt;(ref T field, T value, string propertyName) { if (EqualityComparer&lt;T&gt;.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } // props private string name; public string Name { get { return name; } set { SetField(ref name, value, "Name"); } } } </code></pre> <p>Each property is then just something like:</p> <pre><code> private string name; public string Name { get { return name; } set { SetField(ref name, value, "Name"); } } </code></pre> <p>which isn't huge; it can also be used as a base-class if you want. The <code>bool</code> return from <code>SetField</code> tells you if it was a no-op, in case you want to apply other logic.</p> <hr> <p>or even easier with C# 5:</p> <pre><code>protected bool SetField&lt;T&gt;(ref T field, T value, [CallerMemberName] string propertyName = null) {...} </code></pre> <p>which can be called like this:</p> <pre><code>set { SetField(ref name, value); } </code></pre> <p>with which the compiler will add the <code>"Name"</code> automatically.</p> <hr> <p>C# 6.0 makes the implementation easier:</p> <pre><code>protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } </code></pre> <hr> <p>...and now with C#7:</p> <pre><code>private string name; public string Name { get =&gt; name; set =&gt; SetField(ref name, value); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload