【发布时间】:2023-10-02 17:33:01
【问题描述】:
C#/MVVM 新手,这对我来说没有意义吗?
这是我从 ICommand 继承的 RelayCommand 的实现:
internal class RelayCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action _execute;
public event EventHandler CanExecuteChanged = (sender, e) => {};
public RelayCommand(Action execute) : this(execute, null){ }
public RelayCommand(Action execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter) => (_canExecute == null) ? true : _canExecute(parameter);
public void Execute(object parameter) => _execute();
}
我通过测试发现我根本不能这样做:
public RelayCommand TestCommand;
我必须这样做:
public RelayCommand TestCommand { get; set; }
否则在构造函数中声明命令如下:
TestCommand = new RelayCommand(TestCommandFunction);
public void TestCommandFunction(){}
行不通。为什么会这样?
【问题讨论】:
标签: c# wpf mvvm icommand relaycommand