Why is my event handler null?

1.1k views Asked by At

I've got quite simple problem but gives me a headache and I'm wasting too much time. I've ran out of ideas anyway:) For some reason I can't pass the value of my property variable to my event handler. Here is what I've got , an for me everything is fine but it won't work:( enter image description here enter image description here

Any idea why it's not passing the actual value of the variable? Thanks in advance:)

1

There are 1 answers

1
ycsun On

Just as the name suggests, propertyName should contain the property's name, not value. Also see PropertyChangedEventHandler and PropertyChangedEventArgs on MSDN for more details.

As to why your event handler null, I suspect you haven't subscribed to it. You should have something like the following somewhere in your program:

obj.PropertyChanged += new PropertyChangedEventHandler(obj_PropertyChanged);

private void obj_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
  ....
}

then when obj.Moves changes obj_PropertyChanged will be called.

I understand your confusion, so let me give a little more explanations. Suppose you have two classes A and B, and you want B to be notified when a property of A is changed. Then you can make A implement INotifyPropertyChanged, and make B subscribe to the PropertyChanged event of A, like the following:

public class A: INotifyPropertyChanged
{
  private int moves;
  public int Moves
  {
    get { return moves; }
    set
    {
      if (value != moves) {
        moves = value;
        OnPropertyChanged("Moves");
      }
    }
  }

  public event PropertyChangedEventHandler PropertyChanged;

  private void OnPropertyChanged(string propertyName)
  {
    if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
  }
}

public class B
{
  private A a = new A();

  public B()
  {
    a.PropertyChanged += new PropertyChangedEventHandler(a_PropertyChanged);
  }

  private void a_PropertyChanged(object sender, PropertyChangedEventArgs e)
  {
    ....
  }
}

With the above, B.a_PropertyChanged will be called whenever A.Moves is changed. More precisely, if b is an instance of B, then b.a_PropertyChanged will be called whenever b.a.Moves is changed. Also please note how my implementation of the setter of Moves differs from yours.