使用RelayCommand WPF将不同的命令参数传递给同一命令 [英] Pass different commandparameters to same command using RelayCommand WPF

查看:185
本文介绍了使用RelayCommand WPF将不同的命令参数传递给同一命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我在这里想要实现的是使用相同的命令来执行某些不同类型的代码.我想要区分要执行的代码的方式可以使用commandparameters来完成.当我不得不使用RelayCommand时,我只是看不到如何按照自己的方式做.

So, what I am trying to achieve here is to use the same command to execute some different kind of code. The way I want to distinguish between the code I want to be executed can be done using commandparameters. I just don't see how I can do it the way I want to, when I have to use the RelayCommand.

这意味着,我有2个不同的按钮,两个按钮都使用相同的命令,只是命令参数不同.

This means, that I have 2 different buttons, that both uses the same command, just with different commandparameters.

到目前为止,这是我的XAML:

This is my XAML so far:

<RibbonButton SmallImageSource="../Images/whatever.png" Label="Attribute" Command="{Binding AddItemToNodeCommand}" CommandParameter="Attribute"/>

<RibbonButton SmallImageSource="../Images/whatever.png" Label="Method" Command="{Binding AddItemToNodeCommand}" CommandParameter="Method" />

这是我在ViewModel中拥有的:

This is what I have in my ViewModel:

public ICommand AddItemToNodeCommand { get; private set; }

当然:

AddItemToNodeCommand = new RelayCommand(AddItemToNode);

在调用relayCommand时,是否可以使用某种命令参数?

Is there some way that I can be able to use that commandparameter when calling the relayCommand?

如果您需要更多信息或代码,请询问.

If you need any more information, or code please just ask.

推荐答案

您可以使用lambda表达式来访问CommandParameter ...,请尝试以下操作:

You can use a lambda expression to give you access to the CommandParameter... try this:

AddItemToNodeCommand = new RelayCommand(parameter => AddItemToNode(parameter));

请注意(与所有lambda表达式一样),这里的parameter名称可能是 ...这将是相同的:

Please note that (as with all lambda expressions) the name parameter here could be anything... this would work just the same:

AddItemToNodeCommand = new RelayCommand(p => AddItemToNode(p));

这是因为我们只是在=>之前为其设置了输入参数名称.

This is because we are simply setting the input parameter name for it before the =>.

更新>>>

您尝试过这样吗?:

AddItemToNodeCommand = new RelayCommand<object>(parameter => AddItemToNode(parameter));

最后一个选择就是以与开始时相同的方式调用它:

The last option is just to call it in the same way as you started with:

AddItemToNodeCommand = new RelayCommand(AddItemToNode);

这篇关于使用RelayCommand WPF将不同的命令参数传递给同一命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆