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

怎甘沉沦 提交于 2019-12-06 11:50:01

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.

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.

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

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