检测PropertyChangedEventHandler何时更改

时间:2014-08-29 17:07:22

标签: c# wpf

当我观察变量时,我的PropertyChanged事件正确设置,但在代码的某处,它被重置为null,我不知道如何找出这种情况。

这是代码:

public event PropertyChangedEventHandler PropertyChanged;

  //this is in the NotifyTaskCompletion class, as used from the blog 
 // http://msdn.microsoft.com/en-us/magazine/dn605875.aspx
  private async Task WatchTaskAsync(Task task)
    {
        try
        {
            await task; //After this task, PropertyChanged gets set to a non-null method("Void OnPropertyChanged()")
        }
        catch
        {
        }
      //PropertyChanged, which was set to a value after the task was run, and still not null  during IdentifyCompleted getting set, is now null here
       var propertyChanged = PropertyChanged; 
        if (propertyChanged == null)
            return;
        //other code
}


  //My Watch variable of PropertyChanged is still good after this setter is run.
  public NotifyTaskCompletion<GraphicCollection> IdentifyCompleted
     {
         get { return _IdentifyCompleted; }
         set
         {
             _IdentifyCompleted = value;
         //    _IdentifyCompleted.PropertyChanged+= new PropertyChangedEventHandler(this, new     PropertyChangedEventArgs("IdentifyCompleted")); 
            // NotifyPropertyChanged();
         }
     }

我的主要问题是我不能在PropertyChanged上使用{set; get;}来尝试识别它被设置为null的WHERE。所以我的主要问题是,除非有人看到明显错误的东西,我将如何找到它被设置为null的位置?感谢您的帮助。

修改

根据最后的海报建议,我将代码设置如下:

    private PropertyChangedEventHandler _propertyChanged;
    public event PropertyChangedEventHandler PropertyChanged
    {
        add { _propertyChanged += value; }
        remove { _propertyChanged -= value; }
    }

这就是问题所在。

//this is in my View Model. The ViewModel CONTAINS NotifyTaskCompletion<GraphicCollection> IdentifyCompleted  which in turn implements INotifyPropertyChanged and has its own PropertyChanged that is not getting set

   private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
//This line sets the PopertyChanged in the view model AND in the NotifyTaskCompletion class somehow, but I don't know how it is setting it properly in the NotifyTaskCompletion class in my other project where this code works, When I step through this line in my code, it doesn't trigger
//the add{} of the PropertyChanged in NotifyTaskCompletion, but it DOES in my other project...
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

所以尽管如此,我现在可以看到哪一行应该起作用,但我不知道为什么它不起作用。还有其他想法吗?感谢您的帮助。

1 个答案:

答案 0 :(得分:7)

您可以编写自己的事件访问者:

private PropertyChangedEventHandler propertyChanged;
public event PropertyChangedEventHandler PropertyChanged {
    add { propertyChanged += value; }
    remove { propertyChanged -= value; }
}

然后您可以设置断点。 请注意,这不是线程安全的。