简体   繁体   中英

Property Change event is null even after I registered it

I use INotifyPropertyChanged to notify class when there is any change in a variable of a particular object within it.

Below is the class:

 public class MyClass
 {
        public SecClass MyObj { get; set; }

     //A few more variables
 }

SecClass:

 public class SecClass:INotifyPropertyChanged
 {
    private bool _noti= false;

    public bool Noti
    {
        get { return _noti; }
        set
        {
            _noti= value;
            NotifyPropertyChanged("Noti");
        }
    }

     //A few more variables
    public event PropertyChangedEventHandler PropertyChanged;

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

Here my function that makes the event registration:

    public void Register()
    {
      MyObj.PropertyChanged += MyObj_PropertyChanged;         
    }

Function works and the registration is done, but when it comes to change it displays the Property Change as null (I guess that somewhere registration deleted, before happens change, how can I check this?)

I hooked this together with:

static class Program
{
    static void Main()
    {
        var c = new MyClass();
        c.MyObj = new SecClass();
        c.Register();
        c.MyObj.Noti = !c.MyObj.Noti;
    }
}

adding (for illustration):

private void MyObj_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    Console.WriteLine(e.PropertyName);
}

to MyClass , and:

public event PropertyChangedEventHandler PropertyChanged;

to SecClass (to get them to compile), and it works fine - printing "Noti" at runtime. There is a theoretical thread-race, but it is very unlikely in any sane usage, but recommended usage is:

var handler = PropertyChanged;
if (handler != null)
{
    handler(this, new PropertyChangedEventArgs(name));
}

Also, for info: if you add [CallerMemberName] to that, you don't need to specify the property explicitly:

private void NotifyPropertyChanged([CallerMemberName] string name = null) {...}

with:

NotifyPropertyChanged(); // the compiler adds the "Noti" itself

But fundamentally: "cannot reproduce" - it works fine. I wonder if maybe it relates to your PropertyChanged implementation, since you don't actually show that. In particular, I wonder if you actually have two events: one explicitly implemented. That would mean that it is getting treated differently by your cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM