CommandManager 调用 CanExecuteChanged 事件,如果绑定(bind)到此 ICommand 的按钮从 UI 中消失则事件
命令处理程序
public class CommandHandler : ICommand
{
private readonly Action _action;
private readonly Func<bool> _canExecute;
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute != null)
{
return _canExecute();
}
return false;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_action();
}
}
查看在 View 中,我绑定(bind)到一个 View 模型列表(用于调用)注意:在 UI 上没有问题,Binding 工作正常。(也适用于多次通话)
<ItemsControl ItemsSource="{Binding Path=CallHandlingViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:CallHandlingControl />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
ViewModel CallHandlingViewModel
public class CallHandlingViewModel: BaseViewModel
{
private ICallHandlingModel _model;
public CommandHandler AnswerCommand { get; }
public CommandHandler EndCommand { get; }
public CallHandlingViewModel(IDispatcher dispatcher, ICallHandlingModel model, BsCallEventArgs data) : base(model)
{
Dispatcher = dispatcher;
_model = model;
AnswerCommand = new CommandHandler(() => _model.AnswerCall(), CanAnswerExecute);
EndCommand = new CommandHandler(() => _model.HangUpCall(), CanHangupExecute);
}
private bool CanAnswerExecute()
{
return _model.CheckAction(ActionType.Answer);
}
private bool CanHangupExecute()
{
return _model.CheckAction(ActionType.Drop);
}
}
针对实际问题我有一个电话,它在 UI 上正确显示。单击“EndCommand”按钮后,调用从 UI 中消失(如预期的那样)
现在的问题是:当我在方法“CanAnswerExecute()”中设置断点时,无论何时单击 UI,它都会到达。
据我所知,“CommandManager”有对每个 ICommand 的引用,因此也有对 ViewModel 的引用。但是,当我的 View 模型从列表中消失时,为什么这个引用没有被删除?
只是预感,没有尝试,尝试改变
public CommandHandler AnswerCommand { get; }
public CommandHandler EndCommand { get; }
对于
public ICommand AnswerCommand { get; }
public ICommand EndCommand { get; }
我是一名优秀的程序员,十分优秀!