Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a single generic Command for handling multiple Buttons

I am building a simple Calculator application. I'm also learning how to apply the MVVM pattern in my app.

I would like each one of the "Digit" buttons of my calculator to bind to the same Command, where they would only differ in the digit (Text) of the button that raised the command.

For example, When button "1" is clicked, i would like to receive the notification about it, extract "1" from the Sender's property, and continue the rest of the work needed.

This allows me to define a single method instead of 10 different handlers.

This is not possible as far as what i've seen in all MVVM tutorials till now, since the Command binding does not provide all this information to me when binding to the actual method that will handle the click.

Is there any way to easily do what i require?

like image 796
lysergic-acid Avatar asked Jan 23 '26 21:01

lysergic-acid


1 Answers

Assuming I understand what you're trying to do, you can use the CommandParameter property to let different buttons supply values to the same command. For example:

...
    <Button Content="1" Command="{Binding ButtonClickCommand}" CommandParameter="1"/>

    <!-- Or, bind directly to the button's content using RelativeSource, like so: -->
    <Button Content="2" Command="{Binding ButtonClickCommand}"                    
                        CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Content}"/>
...

And in your command's delegate method:

private void ButtonClickCommandHandler(object parameter)
{
    switch(int.Parse(parameter.ToString()))
    {
        case 1:
        ...
        case 2:
        ...
    }
}
like image 62
Dan J Avatar answered Jan 26 '26 10:01

Dan J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!