【发布时间】:2018-04-12 22:00:48
【问题描述】:
CommmandManager 调用 CanExecuteChanged 事件,如果绑定到此 ICommand 的按钮从 UI 中消失,则为该事件
CommandHandler
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();
}
}
查看 在视图中,我绑定到视图模型列表(用于调用) 注意:在 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。但是,当我的视图模型从列表中消失时,为什么这个引用没有被删除?
【问题讨论】: