0

I have the following DelegateCommand, created with the Prism library.

public class AddressModel : INotifyPropertyChanged
{
    public ICommand MyButtonClickCommand
    {
        get { return new DelegateCommand<object>(FuncToCall); }
    }

    public void FuncToCall(object context)
    {
        //this is called when the button is clicked
        Method1("string1", integer_number1);
    }
}

I have already bonded MyButtonClickCommand to a button in XAML file.

<Button Content="Click me" 
        Command="{Binding MyButtonClickCommand}"/> 

But I would like to use the same MyButtonClickCommand for 2 more buttons instead of creating two additional DelegateCommands MyButtonClickCommand1 & MyButtonClickCommand2.

So what I want is to add string1 and integer_number1 as parameters and call the same ICommand on different buttons like below

<Button Content="Click me" 
        Command="{Binding MyButtonClickCommand("string1", integer_number1)}"/>
<Button Content="Click me 2" 
        Command="{Binding MyButtonClickCommand("string2", integer_number2)}"/>
<Button Content="Click me 3" 
        Command="{Binding MyButtonClickCommand("string3", integer_number3)}"/>
DelusionX
  • 79
  • 8
  • You can pass a single object to the CommandParameter property of the Button, e.g. by a binding or by a direct assignment. That object is passed as argument to the command's Execute handler method. – Clemens Oct 20 '20 at 13:30
  • @Clemens Thanks for your comment. But how the Execute handler will know that "string1" and integer_number1 where to be placed inside the ```FuncToCall()```? – DelusionX Oct 20 '20 at 13:35
  • @Clemens also I think that I cannot use more than 1 time the CommandParameter. Based on my question I have 2 parameters to pass in the DelegateCommand – DelusionX Oct 20 '20 at 13:41

2 Answers2

3

You can pass an instance of any class that could be declared in XAML

public class MyCommandParameter
{
    public int MyInt { get; set; }
    public string MyString { get; set; }
}

to the CommandParameter property of a Button:

<Button Content="Click me" Command="{Binding ...}">
    <Button.CommandParameter>
        <local:MyCommandParameter MyInt="2" MyString="Hello"/>
    </Button.CommandParameter>
</Button>

The MyCommandParameter instance is passed to the Execute handler method's argument:

public void FuncToCall(object parameter)
{
    var param = (MyCommandParameter)parameter;

    // do something with param.MyInt and param.MyString
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
0

Use the CommandParameter property:

<Button Content="Click me 2" 
        Command="{Binding MyButtonClickCommand}"
        CommandParameter="2" />

You could then cast the context parameter to whatever the value of the command parameter is:

public void FuncToCall(object context)
{
    string parameter = context as string;
    if (int.TryParse(parameter, out int number))
    {
        //---
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88