c# - Raise an event whenever a property's value changed? -


there property, it's named imagefullpath1

public string imagefullpath1 {get; set; } 

i'm going fire event whenever value changed. aware of changing inotifypropertychanged, want events.

the inotifypropertychanged interface is implemented events. interface has 1 member, propertychanged, event consumers can subscribe to.

the version richard posted not safe. here how safely implement interface:

public class myclass : inotifypropertychanged {     private string imagefullpath;      protected void onpropertychanged(propertychangedeventargs e)     {         propertychangedeventhandler handler = propertychanged;         if (handler != null)             handler(this, e);     }      protected void onpropertychanged(string propertyname)     {         onpropertychanged(new propertychangedeventargs(propertyname));     }      public string imagefullpath     {         { return imagefullpath; }         set         {             if (value != imagefullpath)             {                 imagefullpath = value;                 onpropertychanged("imagefullpath");             }         }     }      public event propertychangedeventhandler propertychanged; } 

note following things:

  • abstracts property-change notification methods can apply other properties;

  • makes copy of propertychanged delegate before attempting invoke (failing create race condition).

  • correctly implements inotifypropertychanged interface.

if want additionally create notification specific property being changed, can add following code:

protected void onimagefullpathchanged(eventargs e) {     eventhandler handler = imagefullpathchanged;     if (handler != null)         handler(this, e); }  public event eventhandler imagefullpathchanged; 

then add line onimagefullpathchanged(eventargs.empty) after line onpropertychanged("imagefullpath").

since have .net 4.5 there exists callermemberattribute, allows rid of hard-coded string property name in source code:

    protected void onpropertychanged(         [system.runtime.compilerservices.callermembername] string propertyname = "")     {         onpropertychanged(new propertychangedeventargs(propertyname));     }      public string imagefullpath     {         { return imagefullpath; }         set         {             if (value != imagefullpath)             {                 imagefullpath = value;                 onpropertychanged();             }         }     } 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -