Pass different commandparameters to same command using RelayCommand WPF

心已入冬 提交于 2019-12-12 04:38:34

问题


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.

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

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" />

This is what I have in my ViewModel:

public ICommand AddItemToNodeCommand { get; private set; }

and of course:

AddItemToNodeCommand = new RelayCommand(AddItemToNode);

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.


回答1:


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

AddItemToNodeCommand = new RelayCommand(parameter => AddItemToNode(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 =>.


UPDATE >>>

Have you tried it like this?:

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


来源:https://stackoverflow.com/questions/19573380/pass-different-commandparameters-to-same-command-using-relaycommand-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!