2015-01-22 3 views
2

У меня есть две модели ViewModels и одна содержит другую. Внутренняя имеет Microsoft.Practices.Prism.Commands.DelegateCommand под названием PrintCommand. Желательно подписаться на событие CanExecuteChanged этой команды. Эта часть выполняется, как обычно:Не удается подписаться на 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, кажется, не содержат какие-либо живые обработчик, даже если абонент объект все еще существует.
Мне любопытно, почему это происходит?

+0

насчет вашего 'CanExecuteChangedHandler'? Как это выглядит? Это метод или лямбда-выражение? – dymanoid

+0

Простой способ. – dmigo

ответ

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; 
Смежные вопросы