Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The way I have done this in the past is to use our good friend Lambda. By using Expressions we can pass in the properties themselves to your implementation of OnPropertyChanges, and use the Expression tree to extract the property. This gives you compile time checking of the members you are raising the PropertyChanged event for.</p> <p>Of course use of Expression will depend entirely on what type of performance you need.</p> <p>See code snippet below:</p> <pre><code>using System; using System.Linq; using System.ComponentModel; using System.Linq.Expressions; namespace OnNotifyUsingLambda { public class MainClass : INotifyPropertyChanged { public static void Main (string[] args) { new MainClass().Run();} public void Run() { this.PropertyChanged += (sender, e) =&gt; Console.WriteLine(e.PropertyName); MyProperty = "Hello"; } private string myProperty; public string MyProperty { get { return myProperty; } set { myProperty = value; // call our OnPropertyChanged with our lamba expression, passing ourselves. // voila compile time checking that we haven't messed up! OnPropertyChanged(x =&gt; x.MyProperty); } } /// &lt;summary&gt; /// Fires the PropertyChanged for a property on our class. /// &lt;/summary&gt; /// &lt;param name="property"&gt; /// A &lt;see cref="Expression&lt;Func&lt;MainClass, System.Object&gt;&gt;"/&gt; that contains the /// property we want to raise the event for. /// &lt;/param&gt; private void OnPropertyChanged (Expression&lt;Func&lt;MainClass, object&gt;&gt; property) { // pull out the member expression (ie mainClass.MyProperty) var expr = (MemberExpression)property.Body; if (PropertyChanged != null) { // Extract everything after the period, which is our property name. var propName = expr.ToString ().Split (new[] { '.' })[1]; PropertyChanged (this, new PropertyChangedEventArgs(propName)); } } public event PropertyChangedEventHandler PropertyChanged; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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