【发布时间】:2021-07-29 08:23:54
【问题描述】:
我有一个带有视图的基本 MVVM WPF 应用程序,由一个 texbox 和提交按钮组成。两个控件都正确绑定到 ViewModel 中的属性和命令。问题在于 CanSubmit 未触发,因为 CanExecuteChanged 事件处理程序(在 DelegateCommand 中)始终为空。基本上问题是如何正确通知命令在更新 textox 时运行 CanExecute 检查。
public DelegateCommand SubmitCommand => new DelegateCommand(Submit, CanSubmit);
private string _company;
public string Company
{
get => _company;
set
{
SetProperty(ref _company, value);
SubmitCommand.RaiseCanExecuteChanged();
}
}
我的委托命令
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public DelegateCommand(Action<object> execute) : this(execute, null) { }
public virtual bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if(CanExecuteChanged != null) <------ Always null
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
【问题讨论】:
-
也许您可以为您的事件使用用户定义的添加和删除访问器,并在此访问器中设置断点以便更好地了解发生了什么?