tags:

views:

105

answers:

3

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?

+1  A: 

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.

Goblin
Thank you.Umm, is using the content property a good idea? I could imagine the content changing in a multi-language environment. (I haven't gotten so far yet, though.)
christian studer
Hehe - no, as your app expands - that's probably not a good ide. I agree with Veer and Steven to go the Command way when you get a bit farther. "First get it working...".
Goblin
+2  A: 

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.

Steven Robbins
Thank you very much! I'll have a look at commanding too.
christian studer
A: 

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

Veer