如何处理WPF中多个类似按钮上的单击事件? [英] How do I handle click events on multiple similar buttons in WPF?

查看:386
本文介绍了如何处理WPF中多个类似按钮上的单击事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#初学者,正在尝试在WPF中实现数字键盘。它由10个相似的按钮组成:

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在第二种情况下,如何确定单击了哪个按钮?我需要访问发件人对象的什么属性?

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

推荐答案

如果要在后面使用代码,则可以将其连接起来到单个事件处理程序,则可以将发送方转换为Button(或FrameworkElement)并检查其名称属性

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>

然后使用e.OriginalSource(转换为Button或FrameworElement)来检索名称。

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);
}

或者,您可以采用MVVM方法,只需一条命令即可按钮绑定到并传递CommandParameter来区分它们。

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.

这篇关于如何处理WPF中多个类似按钮上的单击事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆