views:

71

answers:

4

I'm looking to fire an event each time a property within my class is SET. I'd like to be able to trigger this same event whenever one of my properties are set. I have (around 12 of them)

I.e.

public class MyClass
{
    private int _myHeight;
    private int _myWidth;

public int myHeight
{
    get { return myHeight; }
    set { myHeight = value;
         //This fires event! 
         }
}
public int myWidth
{
    get { return myWidth; }
    set { myWidth = value;
         //This will fire the same event! 
}

I'm not new to events themselves, but rather new to creating events. I've always used the 'out of the box' events that are used in windows apps. Any ideas?

A: 

Hi, take a look at this question it is what you are lloking for http://stackoverflow.com/questions/2264533/listener-c-like-java/2264547#2264547

IordanTanev
+5  A: 

You should implement INotifyPropertyChanged on your class to achieve this. Here's an example.

Jamie Ide
+1 : Never knew about this interface
contactmatt
A: 

With the INotifyPropertyChanged approach, you have to manually call NotifyPropertyChanged in each of your getters.

I'm not sure, but maybe using reflection (to get notified when a setter is being called) would be a better (but more arcane) idea.

Pooria
+2  A: 

Using INotifyPropertyChange is the right approach (because it is a widely used type in .NET, so anybody can understand what your intent is). However, if you just want some simple code to start with, then the implementation of your class might look like this:

public class MyClass 
{ 
  private int _myHeight; 
  public event EventHandler Changed;

  protected void OnChanged() {
    if (Changed != null) Changed(this, EventArgs.Empty);
  }

  public int myHeight 
  { 
    get { return myHeight; } 
    set {
      myHeight = value; 
      OnChanged();
    } 
  }
  // Repeat the same pattern for all other properties
} 

This is the most straightforward way to write the code (which may be good for learning and bad for larger real-world applications).

Tomas Petricek
This is indeed the normal way to do it. I'd also encourage you to check that mHeight is actually changing to a different value before you set the field and raise the event. Otherwise, you can get stuck in infinite event cascades if the UI listens to the event and also sets the member.
munificent
Good point - checking if the value actually changed is quite useful.
Tomas Petricek