无法订阅 DelegateCommand.CanExecuteChanged

Can't subscribe to DelegateCommand.CanExecuteChanged

我有两个 ViewModel,一个包含另一个。里面有一个叫 PrintCommandMicrosoft.Practices.Prism.Commands.DelegateCommand。希望订阅此命令的 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 似乎不包含任何活动的处理程序,即使订阅者对象仍然存在。
我有点好奇,为什么会这样?

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;