问题
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