Christian Studer
Christian Studer

Reputation: 25597

How do I handle click events on multiple similar buttons in WPF?

I'm a C# beginner and am trying to implement a numeric pad in WPF. It consists of 10 similar buttons:

<Button Content="0" Name="button0" Click="anyButtonClicked" />
<Button Content="1" Name="button1" Click="anyButtonClicked" />
<Button Content="2" Name="button2" Click="anyButtonClicked" />
...
<Button Content="9" Name="button9" Click="anyButtonClicked" />

What is the best practise to handle all those buttons? Do I build a function in the code behind for each one (Which would be mostly boring and repeating myself), or do I build one to handle any button clicked?

In the second case, how do I identify which button was clicked? What property of the sender object do I need to access?

Upvotes: 1

Views: 5517

Answers (3)

Amsakanna
Amsakanna

Reputation: 12934

You really need to go by the Command approach because you may need it for key presses also.

Upvotes: 1

Steven Robbins
Steven Robbins

Reputation: 26599

If you want to use code behind then you can hook it up to a single event handler, you can then cast sender to a Button (or a FrameworkElement) and check its Name property.

Expanding on Goblin's answer below; if you want to stick with code behind and events you can define the event on a parent panel:

<StackPanel Button.Click="anyButtonClicked">
    <Button Content="0" Name="button0"/>
    <Button Content="1" Name="button1"/>
    <Button Content="2" Name="button2"/>
    ...
    <Button Content="9" Name="button9"/>
</StackPanel>

Then use e.OriginalSource, cast as a Button or FrameworElement, to retrieve the name.

private void anyButtonClicked(object sender, RoutedEventArgs e)
{
    var source = e.OriginalSource as FrameworkElement;

    if (source == null)
        return;

    MessageBox.Show(source.Name);
}

Alternatively you could take the MVVM approach, have a single command that all of your buttons are bound to, and pass a CommandParameter to differentiate them.

Upvotes: 5

Goblin
Goblin

Reputation: 8022

You handle the Button.Click event in the Parent control:

<StackPanel Button.Click="anyButtonClicked">
    <Button Content="0" Name="button0"/>
    <Button Content="1" Name="button1"/>
    <Button Content="2" Name="button2"/>
    ...
    <Button Content="9" Name="button9"/>
</StackPanel>

Then in your eventhandler - you can check e.OriginalSource for the button pressed.

EDIT: As for your question as to how to handle it - you could use the Content-property of the button pressed to figure out the key and then use that to perform your logic.

Upvotes: 2

Related Questions