即使我注册后,Property Change事件也为null

时间:2013-04-03 11:25:40

标签: c# wpf inotifypropertychanged

当其中的特定对象的变量发生任何变化时,我使用INotifyPropertyChanged来通知类。

以下是课程:

 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));
       }
    }
 }

这是我的事件注册事件:

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

功能正常工作并完成注册,但是当涉及到更改时,它会将Property Change显示为null(我想某处注册已删除,在发生更改之前,我该如何检查?)

1 个答案:

答案 0 :(得分:2)

我把它连在一起:

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

添加(用于说明):

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

MyClass,并且:

public event PropertyChangedEventHandler PropertyChanged;

SecClass(让他们编译),它运行正常 - 在运行时打印"Noti" 是一个理论上的线程竞争,但在任何合理的使用中它都非常,但推荐的用法是:

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

此外,有关信息:如果您向其添加[CallerMemberName],则无需明确指定该属性:

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

使用:

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

但从根本上说:"无法重现" - 它工作正常。我想知道它是否与您的PropertyChanged实施有关,因为您实际上并没有表明这一点。特别是,我想知道你是否真的有 两个 事件:一个明确实现。这意味着你的演员会以不同的方式对待它。