用于更新TextBox的RelayCommand

时间:2016-02-03 09:31:44

标签: c# wpf relaycommand

我是WPF的新手,特别是Commands,我现在有任务为按钮构建一个RelayCommand。我应该知道我需要将逻辑与UI分开。我只有2个文本框和一个textBlock,用户在框中写下名称并单击按钮以在文本块中显示它们。我的任务是阅读RelayCommand并实现它,但我真的不明白它是如何工作的。我的Logic.cs类中有一个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();
}

2 个答案:

答案 0 :(得分:2)

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

我假设Button所在的视图,其DataContext设置为Logic.cs中的类,因此我假设Logic.cs包含viewmodel。因此,在viewmodel中添加一个新属性:

public ICommand UpdateTextCommand { get; private set; }

在viewmodel的构造函数中,您初始化此命令:

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

在视图(XAML)中绑定Button的{​​{1}}属性:

Command

当然我不熟悉你的应用程序的结构,这种绑定可能会失败。但这是指挥的总体思路。

更新:构造函数是没有返回类型的方法(甚至不是<Button Content="Click me to change the TextBlock" Command="{Binding UpdateTextCommand}" /> )。每当您实例化voidnew该方法运行时。

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

Logic

对于public Logic() { // Statements here } ,这是构造函数:

RelayCommand

答案 1 :(得分:1)

您需要在开始使用MVVM之前实现要在ViewModel中调用的方法,就像使用CodeBehind-File一样。

然后你需要在Viewmodel中创建一个ICommand作为属性(之后为Binding):

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table>
  <tr>
    <th class="test">Filename</th>
    <th>value</th>
  </tr>
  <tr>
    <td class="test">File1</td>
    <td>Test</td>
  </tr>
  <tr>
    <td class="test">File1</td>
    <td>Test</td>
  </tr>
  <tr>
    <td class="test">File1</td>
    <td>Test</td>
  </tr>
</table>

在(viewmodel的)构造函数中,您需要创建RelayCommand对象:

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

OnUpdateText是您要调用的方法。

接下来,您必须使用正确的参数创建构造函数。 如果你的OnUpdateText看起来像这样:

relUpdateText = new RelayCommand(OnUpdateText);

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

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

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

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

如果您有更多参数,则必须使用转换器。