Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net Can';t订阅DelegateCommand.CanExecuteChanged_.net_Wpf_Prism_Weak References_Delegatecommand - Fatal编程技术网

.net Can';t订阅DelegateCommand.CanExecuteChanged

.net Can';t订阅DelegateCommand.CanExecuteChanged,.net,wpf,prism,weak-references,delegatecommand,.net,Wpf,Prism,Weak References,Delegatecommand,我有两个ViewModels,其中一个包含另一个。内部有一个名为PrintCommand的Microsoft.Practices.Prism.Commands.DelegateCommand。最好订阅此命令的CanExecuteChanged事件。本部分照常实施: OneViewModel.PrintCommand.CanExecuteChanged += CanExecuteChangedHandler; 问题是此订阅不起作用。 反编译的CanExecuteChanged如下所示: pu

我有两个ViewModels,其中一个包含另一个。内部有一个名为
PrintCommand
Microsoft.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);  
  }  
}  
当我调试时,在订阅后的几个步骤后,
\u CanExecuteChangedHandler
似乎不包含任何活动的处理程序,即使订阅对象仍然存在。

我有点好奇,为什么会这样

答案在
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.
然后像这样使用它:

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

您的
CanExecuteChangedHandler如何?看起来怎么样?这是一个方法还是一个lambda表达式?
this.commandCanExecuteChangedHandler = new EventHandler(this.CommandCanExecuteChanged);
this.command.CanExecuteChanged += this.commandCanExecuteChangedHandler;