我是新来的WPF,特别是命令,我现在有任务来为按钮构建一个RelayCommand。我应该知道我需要从UI中分离逻辑。我只有2个文本框和一个textBlock,用户在框中写入名称,然后单击按钮将其显示在文本块中。我的任务是阅读有关RelayCommand并实施它,但我真的不明白它是如何工作的。我在我的Logic.cs类中有一个UpdateName方法,如何在RelayCommand中使用它?我所拥有的是具有实现的ICommand接口的RelayCommand.cs。 这是我在网上找到的代码,但我真的不知道要放在哪里。用于更新文本框的RelayCommand
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
private Action methodToExecute;
private Func<bool> canExecuteEvaluator;
public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator)
{
this.methodToExecute = methodToExecute;
this.canExecuteEvaluator = canExecuteEvaluator;
}
public RelayCommand(Action methodToExecute)
: this(methodToExecute, null)
{
}
public bool CanExecute(object parameter)
{
if (this.canExecuteEvaluator == null)
{
return true;
}
else
{
bool result = this.canExecuteEvaluator.Invoke();
return result;
}
}
public void Execute(object parameter)
{
this.methodToExecute.Invoke();
}
是的,DataContext被设置为逻辑类。我添加了属性,但是我在哪里初始化命令? Logic.cs中的视图模型的构造器在哪里?对不起,我真的很新鲜。绑定部分我明白。 – tweedledum11
更新了答案。 –
好吧,我在Logic构造函数中初始化了命令,通过UpdateText()来表示我的自定义方法UpdateName是否正确?我的Visual Studio让我改变它为:UpdateTextCommand = new RelayCommand(delegate(object obj){UpdateName();},null);这是为什么?之前的一个没有工作。 – tweedledum11