用于更新 TextBox 的 RelayCommand

RelayCommand for updating a TextBox

我是 WPF 的新手,尤其是命令,我现在有任务为按钮构建 RelayCommand。我应该知道我需要将逻辑与 UI 分开。我只有 2 个文本框和一个文本块,用户在框中写下名称,然后单击按钮将它们显示在文本块中。我的任务是阅读 RelayCommand 并实现它,但我真的不明白它是如何工作的。我的 Logic.cs class 中有一个 UpdateName 方法,如何在 RelayCommand 中使用它?我所拥有的只是带有已实现的 ICommand 接口的 RelayCommand.cs。 这是我在网上找到的代码,但是我真的不知道放在哪里。

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();
}

您没有在 RelayCommand 本身中添加任何逻辑。

我假设 Button 所在的视图的 DataContext 设置为 Logic.cs 中的 class,所以我假设 Logic.cs 包含视图模型。所以在视图模型中你添加了一个新的 属性:

public ICommand UpdateTextCommand { get; private set; }

在视图模型的构造函数中初始化此命令:

UpdateTextCommand = new RelayCommand(() => this.UpdateName(), null);

并在视图 (XAML) 中绑定 ButtonCommand 属性:

<Button Content="Click me to change the TextBlock" Command="{Binding UpdateTextCommand}" />

当然我不熟悉你的应用程序的结构,这个绑定可能会失败。但这是指挥的一般想法。

Update:构造函数是没有return类型的方法(甚至没有void)。每当您实例化 (new) 一个 class 时,该方法就会运行。

对于 Logic 应该是(如果 class 名称是 Logic):

public Logic()
{
    // Statements here
} 

对于RelayCommand,这是构造函数:

public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator)

您需要在 ViewModel 中实现您想要调用的方法,就像您在开始使用 MVVM 之前使用代码隐藏文件所做的那样。

然后您需要在您的 Viewmodel 中创建一个 ICommand 作为 属性(用于之后的绑定):

private RelayCommand relUpdateText;
public ICommand CUpdateTextCommand { get { return relUpdateText; } }

在您的(视图模型的)构造函数中,您需要创建 RelayCommand 对象:

relUpdateText = new RelayCommand(OnUpdateText);

OnUpdateText 是您要调用的方法。

接下来您必须创建一个具有正确参数的构造函数。 如果您的 OnUpdateText 看起来像这样:

private void OnUpdateText(string text){...}

您的 RelayCommand 构造函数应如下所示:

private Action<String> exec;
public RelayCommand(Action<String> exec)
{
   this.exec = exec;
}

如您所见,Action 需要与它封装的方法相同的参数。 最后你还应该检查事件是否不为空:

public void Execute(object parameter)
{
    if(exec != null) exec(paramters as string);
}

如果你有更多的参数,你将不得不使用转换器。