使用 ViewModel 中定义的 RelayCommand 传递参数(来自 Josh Smith 示例)

发布于 2024-07-19 03:20:48 字数 1903 浏览 1 评论 0原文

我想使用 RelayCommand 将应用程序的 XAML(视图)中定义的参数传递给 ViewModel 类。 我遵循Josh Smith关于MVVM的优秀文章并实现了以下内容。

XAML 代码

        <Button 
        Command="{Binding Path=ACommandWithAParameter}"
        CommandParameter="Orange"
        HorizontalAlignment="Left" 
        Style="{DynamicResource SimpleButton}" 
        VerticalAlignment="Top" 
        Content="Button"/>

ViewModel 代码

  public RelayCommand _aCommandWithAParameter;
  /// <summary>
  /// Returns a command with a parameter
  /// </summary>
  public RelayCommand ACommandWithAParameter
  {
     get
     {
        if (_aCommandWithAParameter == null)
        {
           _aCommandWithAParameter = new RelayCommand(
               param => this.CommandWithAParameter("Apple")
               );
        }

        return _aCommandWithAParameter;
     }
  }

  public void CommandWithAParameter(String aParameter)
  {
     String theParameter = aParameter;
  }
  #endregion

我在 CommandWithAParameter 方法中设置了一个断点,并观察到 ​​aParameter 被设置为“Apple”,而不是“Orange”。 这看起来很明显,因为 CommandWithAParameter 方法是用文字字符串“Apple”调用的。

但是,查找执行堆栈,我可以看到“Orange”,我在XAML中设置的CommandParameter是ICommand Execute接口方法的RelayCommand实现的参数值。

也就是说,执行堆栈下面的方法中的参数值为“Orange”,

  public void Execute(object parameter)
  {
     _execute(parameter);
  }

我想弄清楚的是如何创建 RelayCommand ACommandWithAParameter 属性,以便它可以使用定义在中的 CommandParameter“Orange”调用 CommandWithAParameter 方法XAML。

有没有办法做到这一点?

我为什么要这样做? “即时本地化”的一部分 在我的特定实现中,我想创建一个可以绑定到多个按钮的 SetLanguage RelayCommand。 我想将两个字符语言标识符(“en”、“es”、“ja”等)作为 CommandParameter 传递,并为 XAML 中定义的每个“设置语言”按钮定义该标识符。 我希望避免为支持的每种语言创建 SetLanguageToXXX 命令,并将两个字符语言标识符硬编码到 ViewModel 中的每个 RelayCommand 中。

I would like to pass a parameter defined in the XAML (View) of my application to the ViewModel class by using the RelayCommand. I followed Josh Smith's excellent article on MVVM and have implemented the following.

XAML Code

        <Button 
        Command="{Binding Path=ACommandWithAParameter}"
        CommandParameter="Orange"
        HorizontalAlignment="Left" 
        Style="{DynamicResource SimpleButton}" 
        VerticalAlignment="Top" 
        Content="Button"/>

ViewModel Code

  public RelayCommand _aCommandWithAParameter;
  /// <summary>
  /// Returns a command with a parameter
  /// </summary>
  public RelayCommand ACommandWithAParameter
  {
     get
     {
        if (_aCommandWithAParameter == null)
        {
           _aCommandWithAParameter = new RelayCommand(
               param => this.CommandWithAParameter("Apple")
               );
        }

        return _aCommandWithAParameter;
     }
  }

  public void CommandWithAParameter(String aParameter)
  {
     String theParameter = aParameter;
  }
  #endregion

I set a breakpoint in the CommandWithAParameter method and observed that aParameter was set to "Apple", and not "Orange". This seems obvious as the method CommandWithAParameter is being called with the literal String "Apple".

However, looking up the execution stack, I can see that "Orange", the CommandParameter I set in the XAML is the parameter value for RelayCommand implemenation of the ICommand Execute interface method.

That is the value of parameter in the method below of the execution stack is "Orange",

  public void Execute(object parameter)
  {
     _execute(parameter);
  }

What I am trying to figure out is how to create the RelayCommand ACommandWithAParameter property such that it can call the CommandWithAParameter method with the CommandParameter "Orange" defined in the XAML.

Is there a way to do this?

Why do I want to do this? Part of "On The Fly Localization"
In my particular implementation I want to create a SetLanguage RelayCommand that can be bound to multiple buttons. I would like to pass the two character language identifier ("en", "es", "ja", etc) as the CommandParameter and have that be defined for each "set language" button defined in the XAML. I want to avoid having to create a SetLanguageToXXX command for each language supporting and hard coding the two character language identifier into each RelayCommand in the ViewModel.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

久夏青 2024-07-26 03:20:48

我不明白为什么你首先需要指定 lambda 这么复杂。 为什么不这样做:

if (_aCommandWithAParameter == null)
{           
    _aCommandWithAParameter = new RelayCommand<object>(CommandWithAParameter);
}

private void CommandWithAParameter(object state)
{
    var str = state as string;
}

I don't understand why you have the extra complexity of specifying the lambda in the first place. Why not just do this:

if (_aCommandWithAParameter == null)
{           
    _aCommandWithAParameter = new RelayCommand<object>(CommandWithAParameter);
}

private void CommandWithAParameter(object state)
{
    var str = state as string;
}
标点 2024-07-26 03:20:48

您将 lambda 中的参数传递给命令,如下所示:

if (_aCommandWithAParameter == null)
{           
    _aCommandWithAParameter = new RelayCommand(               
        param => this.CommandWithAParameter(param)
        );        
}

You'll pass the param in the lambda to the command like so:

if (_aCommandWithAParameter == null)
{           
    _aCommandWithAParameter = new RelayCommand(               
        param => this.CommandWithAParameter(param)
        );        
}
山有枢 2024-07-26 03:20:48

之前在这里发布的任何内容都对我有用。

事实证明,所有答案都缺少 RelayCommand 之后的

这对我有用:

public RelayCommand<object> OKCommand
{
    get
    {
        if (_okCommand == null)
            _okCommand = new RelayCommand<object>(OkCommand_Execute);
        return _okCommand;
    }
}
private RelayCommand<object> _okCommand = null;

private void OkCommand_Execute(object obj)
{
    Result = true;
}

如果您想使用 CanExecute 方法,请使用以下代码:

_okCommand = new RelayCommand<object>(OkCommand_Execute, OkCommand_CanExecute);

private bool OkCommand_CanExecute(object obj) { }

Nothing posted here before worked for me.

Turns out, all answers are missing the <object> after RelayCommand!

This works for me:

public RelayCommand<object> OKCommand
{
    get
    {
        if (_okCommand == null)
            _okCommand = new RelayCommand<object>(OkCommand_Execute);
        return _okCommand;
    }
}
private RelayCommand<object> _okCommand = null;

private void OkCommand_Execute(object obj)
{
    Result = true;
}

If you want to use aCanExecute method, use the following code:

_okCommand = new RelayCommand<object>(OkCommand_Execute, OkCommand_CanExecute);

private bool OkCommand_CanExecute(object obj) { }
她比我温柔 2024-07-26 03:20:48

这是命令参数的一个简单解决方案,因为我正在寻找有关该主题的帮助。 我在网上找不到任何足够简单的东西。 当您使用中继命令时,以下解决方案效果很好。
我有一些超链接,我需要获取使用命令参数单击的 url 值。

步骤 1:在中继命令中,创建一个简单的属性来保存参数对象值。 您可以将其称为“参数值”或任何您喜欢的名称。

public object ParameterValue
{
  get;
  set;
}

步骤 2:在 RelayCommand 类的 Execute 方法中,将上面创建的值或属性设置为 Execute 方法中的参数。

readonly Action<object> m_execute;       // Action to execute

public void Execute(object parameter)
 {
   this.ParameterValue = parameter;
   m_execute(parameter);
 }

步骤 3:现在,您可以将 xaml 中的 CommandParameter 绑定到执行命令时想要检索的任何值。
示例:

<TextBlock>
  <Hyperlink Command="{Binding Path=NavigateUrlCmd}"
             CommandParameter="{Binding ElementName=tbwebsite, Path=Text}">
    <TextBlock Name="tbwebsite" Text="{Binding Path=website}"/>
  </Hyperlink>
</TextBlock> 

如果您有一个名为 ChickenCommand 的命令,则执行时您可以访问参数:
ChickenCommand.ParameterValue

我希望这对某人有帮助。 感谢您之前的所有帮助。

Here is a simple solution for the commandparameter as I was looking for help on the subject. I could not find anything online that was simple enough. The following solution works well when you are using a relaycommand.
I had a few hyperlinks for which I needed to get the url value that was clicked using the command parameter.

Step 1: In your relay command, create a simple property that will hold the parameter object value. You could call it parametervalue or any name that you prefer.

public object ParameterValue
{
  get;
  set;
}

Step 2: In the Execute Method of the RelayCommand class, set the value or the property created above to the parameter from the Execute method.

readonly Action<object> m_execute;       // Action to execute

public void Execute(object parameter)
 {
   this.ParameterValue = parameter;
   m_execute(parameter);
 }

Step 3: Now when you can bind the CommandParameter in xaml to any value you want to retrieve when the command is executed.
example:

<TextBlock>
  <Hyperlink Command="{Binding Path=NavigateUrlCmd}"
             CommandParameter="{Binding ElementName=tbwebsite, Path=Text}">
    <TextBlock Name="tbwebsite" Text="{Binding Path=website}"/>
  </Hyperlink>
</TextBlock> 

If you have a command called chickenCommand, when executed you could access the parameter:
chickenCommand.ParameterValue

I hope this helps somebody. Thank you for all your previous help.

ら栖息 2024-07-26 03:20:48

我只是想推销我的观点,看看这是否有效...

http://mywpf-visu.blogspot.com/2009/12/relay-command-how-to-pass-parameter.html

I am just trying to sell my point, check this out whether this works...

http://mywpf-visu.blogspot.com/2009/12/relay-command-how-to-pass-parameter.html

Spring初心 2024-07-26 03:20:48

我无法用对方法名称的引用替换 lamda 表达式,但会出现编译错误。 显然,并且毫不奇怪,非静态方法名称引用不能用来代替 lambda。 我几乎不认为这是“增加了复杂性”。 持续通过 lamdas 对我来说很有意义。

I cannot substitute a reference to the method name for the lamda expression withing a compile error. Apparently, and by no means surprisingly, a non-static method name reference cannot be used in place of a lambda. I hardly see it as "added complexity". Consistently passing lamdas makes sense to me.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文