2

我有两个 ViewModel,一个包含另一个。内层有一个Microsoft.Practices.Prism.Commands.DelegateCommandPrintCommand。最好订阅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似乎不包含任何活动处理程序,即使订阅者对象仍然存在。
我有点好奇,为什么会这样?

4

1 回答 1

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;
于 2015-01-23T08:16:18.073 回答