简体   繁体   中英

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?

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:
        ...
    }
}

Just provide the digit as a Button.CommandParameter . (Which is passed as a method parameter of ICommand.Execute (and CanExecute ))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM