c# - How to rise PropertyChanged event without passing property name as a string? -


in wpf use following pattern bindable properties:

private foo _bar = new foo(); public foo bar {     { return _bar; }     set     {         _bar = value;         onpropertychanged();     } }  public void onpropertychanged([callermembername] string property = "") {     if (propertychanged != null)         propertychanged(this, new propertychangedeventargs(property)); } 

callermembernameattribute nice magic, generating "bar" parameter setter name.

however, there properties without setter or dependent properties:

private foo _bar; public foo bar {     { return _bar; }     set     {         _bar = value;         onpropertychanged();     } }  public bool isbarnull {     { return _bar == null; } } 

in given example, when bar changed isbarnull needs event too. can add onpropertychanged("isbarnull"); bar setters, ... using string properties is:

  • ugly;
  • hard refactor (vs's "rename" not rename property name in string);
  • can source of kind of mistakes.

wpf exists long. there no magical solution yet (similar callermembernameattribute)?

use c# 6 , nameof feature:

onpropertychange(nameof(isbarnull)); 

that generates equivalent code to:

onpropertychange("isbarnull"); 

... without fragility.

if you're stuck on earlier versions of c#, can use expression trees this, regard bit of hack , potential performance issue (as tree recreated on each call). nameof doesn't require library support, new compiler - if upgrade vs 2015 (or later, dear readers future...) should fine.


Comments