无法订阅DelegateCommand.CanExecuteChanged

时间:2015-01-22 15:31:41

标签: .net wpf prism weak-references delegatecommand

我有两个ViewModel,另一个包含另一个。内部的Microsoft.Practices.Prism.Commands.DelegateCommand名为PrintCommand。需要订阅此命令的CanExecuteChanged事件。这部分照常实施:

OneViewModel.PrintCommand.CanExecuteChanged += CanExecuteChangedHandler;  

问题是这个订阅不起作用。 已解压缩的CanExecuteChanged如下所示:

public event EventHandler CanExecuteChanged  
{  
  add  
  {  
    WeakEventHandlerManager.AddWeakReferenceHandler(ref this._canExecuteChangedHandlers, value, 2);  
  }  
  remove  
  {  
    WeakEventHandlerManager.RemoveWeakReferenceHandler(this._canExecuteChangedHandlers, value);  
  }  
}  

当我调试时,在订阅后的几个步骤之后_canExecuteChangedHandlers似乎不包含任何活动处理程序,即使订阅者对象仍然存在。
我有点好奇,为什么会这样?

1 个答案:

答案 0 :(得分:2)

答案在CanExecuteChanged的说明中找到。这是:

/// When subscribing to the <see cref="E:System.Windows.Input.ICommand.CanExecuteChanged"/> event using
///             code (not when binding using XAML) will need to keep a hard reference to the event handler. This is to prevent
///             garbage collection of the event handler because the command implements the Weak Event pattern so it does not have
///             a hard reference to this handler. An example implementation can be seen in the CompositeCommand and CommandBehaviorBase
///             classes. In most scenarios, there is no reason to sign up to the CanExecuteChanged event directly, but if you do, you
///             are responsible for maintaining the reference.

这意味着我们应该有一个很难的参考:

private readonly EventHandler commandCanExecuteChangedHandler;

并像这样使用它:

this.commandCanExecuteChangedHandler = new EventHandler(this.CommandCanExecuteChanged);
this.command.CanExecuteChanged += this.commandCanExecuteChangedHandler;