Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Don't forget one thing : <code>PropertyChanged</code> event is mainly consumed by components that will <strong>use reflection</strong> to get the value of the named property.</p> <p>The most obvious example is databinding.</p> <p>When you fire <code>PropertyChanged</code> event, passing the name of the property as a parameter, you should know that <em>the subscriber of this event is likely to use reflection</em> by calling, for instance, <code>GetProperty</code> (at least the first time if it uses a cache of <code>PropertyInfo</code>), then <code>GetValue</code>. This last call is a dynamic invocation (MethodInfo.Invoke) of the property getter method, which costs more than the <code>GetProperty</code> which only queries meta data. (Note that data binding relies on the whole <a href="http://msdn.microsoft.com/en-us/library/ms171819.aspx" rel="noreferrer">TypeDescriptor</a> thing -- but the default implementation uses reflection.)</p> <p>So, of course using hard code property names when firing PropertyChanged is more efficient than using reflection for dynamically getting the name of the property, but IMHO, it is important to balance your thoughts. In some cases, the performance overhead is not that critical, and you could benefit from some kind on strongly typed event firing mechanism.</p> <p>Here is what I use sometimes in C# 3.0, when performances would not be a concern :</p> <pre><code>public class Person : INotifyPropertyChanged { private string name; public string Name { get { return this.name; } set { this.name = value; FirePropertyChanged(p =&gt; p.Name); } } private void FirePropertyChanged&lt;TValue&gt;(Expression&lt;Func&lt;Person, TValue&gt;&gt; propertySelector) { if (PropertyChanged == null) return; var memberExpression = propertySelector.Body as MemberExpression; if (memberExpression == null) return; PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name)); } public event PropertyChangedEventHandler PropertyChanged; } </code></pre> <p>Notice the use of the expression tree to get the name of the property, and the use of the lambda expression as an <code>Expression</code> :</p> <pre><code>FirePropertyChanged(p =&gt; p.Name); </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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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