0

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为空(我猜某处注册已删除,在发生更改之前,我该如何检查?)

4

1 回答 1

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实施有关,因为您实际上并没有表现出来。特别是,我想知道您是否真的有两个事件:一个是显式实现的。这意味着你的演员会以不同的方式对待它。

于 2013-04-03T11:33:31.613 回答