Pass three parameters to Prism DelegateCommand to use the same command on different button commands [MVVM mode]

1.2k Views Asked by At

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)}"/>
2

There are 2 best solutions below

0
On BEST ANSWER

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
}
5
On

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))
    {
        //---
    }
}