2013-04-03 24 views
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为空(我猜somewhe重新注册删除,之前发生的变化,我怎么能检查)

+0

显示一些代码,请在您注册你的意思是像'Register'方法的事件处理程序 –

+1

@ bash.d? –

+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实现有关,因为你实际上并没有表现出来。特别是,我不知道你实际上有事件:一个明确的实施。那就意味着你的演员会受到不同的对待。