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

扶醉桌前 提交于 2019-12-07 21:21:54

问题


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:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/3021291/how-do-i-handle-click-events-on-multiple-similar-buttons-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!