【问题标题】:Creating a command using RelayCommand with multiple tasks:使用带有多个任务的 RelayCommand 创建命令:
【发布时间】:2015-08-20 06:58:45
【问题描述】:

我正在使用 RelayCommand(出于某种原因在我的代码中称为 CommandRelay),正如 Josh Smith 的旧 MVVM 文章中所述。在我的一个工作区中,我有一个接受任何输入的文本框,当按下回车键时,该文本框将被清除,应该出现一个消息框,其中包含“command evoked {0}”,其中 {0} 是文本框。此外,还应将此属性添加到历史字符串中,该字符串用作同一视图中文本块的文本属性。我已经设法让消息框正常工作,但是,由于我是 WPF 和 MVVM 的新手,我不确定如何正确地将更多任务添加到我的命令中。

这里是相关的 XAML:

<TextBox Background="Transparent" BorderBrush="{StaticResource brushWatermarkBorder}" Name="txtUserEntry">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding BindKeyCommand}"
                    CommandParameter="{Binding ElementName=txtUserEntry, Path=Text}"
                    Key="Return"
                    Modifiers=""/>
    </TextBox.InputBindings>
</TextBox>

以及ViewModel中的相关命令:

CommandRelay _BindKeyCommand;
    public ICommand BindKeyCommand
    {
        get
        {
            _BindKeyCommand = new CommandRelay(param => MessageBox.Show(string.Format("Command invoked : {0}", param))); 
            return this._BindKeyCommand;
        }
    }

这会成功返回一个带有文本的消息框。

我已经尝试了几种方法来从该命令中获取多个操作,最明显的是尝试将多个操作传递给 RelayCommand 类,但这也很明显,不起作用。因此,我尝试将 Param 传递给单独的 Execute 函数,如下所示:

CommandRelay _BindKeyCommand;
public ICommand BindKeyCommand
{
    get
    {
        _BindKeyCommand = new CommandRelay(param => this.ExecuteBindKeyCommand(param)); 
        return this._BindKeyCommand;
    }
}
public void ExecuteBindKeyCommand(string param)
{
    MessageBox.Show(string.Format("CommandInvoked: {0}", param));
    // MORE TASKS HERE
}

这肯定会让我用这个命令做很多事情。但是,我在这一行上使用此方法时出错;

_BindKeyCommand = new CommandRelay(param => this.ExecuteBindKeyCommand(param));

“WPFproject.ViewModels.CLIViewModel.ExecuteBindKeyCommand(string)”的最佳重载方法匹配有一些无效参数。

有人可以帮我解决这个问题吗,有人可以建议是否有更合适的方式来做我希望实现的事情(向这个命令添加更多任务)。

【问题讨论】:

  • 你试过了吗:_BindKeyCommand = new CommandRelay(param => this.ExecuteBindKeyCommand((string)param)); ?
  • 卫生署!感谢您的建议,如果您将此作为答案发布,我将接受。您是否也同意添加更多任务的方法是最佳的?
  • Mike Easton 已作为答案发布,我会接受他的答案,但 +1 给你。
  • “最优”是什么意思?一个函数绝对可以做不止一项工作。
  • 谢谢,只是确保没有我应该使用的一些晦涩的替代方法,因为我是新手。感谢您的重申。

标签: c# wpf xaml mvvm relaycommand


【解决方案1】:

CommandParameter 始终是 object,因此您必须将其转换为您需要的任何类型。

在您的情况下,您可以将参数转换为 string,如下所示:

new CommandRelay(param => this.ExecuteBindKeyCommand((string)param)); 

或者,最好将方法更改为接受object 参数,然后在方法中将其转换为string

public void ExecuteBindKeyCommand(object param)
{
    MessageBox.Show(string.Format("CommandInvoked: {0}", param));

    // MORE TASKS HERE
}    

话虽如此,string.Format 无论如何都接受对象,因此您无需担心这一点。

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多