在 WPF 中,我可以像在 Javascript/Jquery 中一样将相同的点击处理程序一次附加到多个按钮吗? [英] In WPF can I attach the same click handler to multiple buttons at once like I can in Javascript/Jquery?

查看:21
本文介绍了在 WPF 中,我可以像在 Javascript/Jquery 中一样将相同的点击处理程序一次附加到多个按钮吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个按钮而不是做

this.button1.Click += new System.EventHandler(this.button_Click);
this.button2.Click += new System.EventHandler(this.button_Click);
etc.
this.button10.Click += new System.EventHandler(this.button_Click);

我希望能够在伪代码中做这样的事情:

I'd like to be able to do something like this in pseudo-code:

this.button*.Click += new System.EventHandler(this.button_Click);

在 Javascript 中,WPF 中可能有类似的东西吗?

In Javascript it is possible is there something like that in WPF ?

推荐答案

在 WPF 中,Button.Click 是一个 路由事件,这意味着事件被路由到可视化树上,直到它被处理.这意味着您可以在 XAML 中添加事件处理程序,如下所示:

In WPF, Button.Click is a routed event, which means that the event is routed up the visual tree until it's handled. That means you can add an event handler in your XAML, like this:

<StackPanel Button.Click="button_Click">
    <Button>Button 1</Button>
    <Button>Button 2</Button>
    <Button>Button 3</Button>
    <Button>Button 4</Button>
</StackPanel>

现在所有按钮都将为其 Click 事件共享一个处理程序 (button_Click).

Now all the buttons will share a single handler (button_Click) for their Click event.

这是跨位于同一父容器中的一组控件处理同一事件的简单方法.如果你想从代码中做同样的事情,你可以使用 AddHandler 方法,就像这样:

That's an easy way to handle the same event across a group of controls that live in the same parent container. If you want to do the same thing from code, you can use the AddHandler method, like this:

AddHandler(Button.ClickEvent, new RoutedEventHandler( button_Click));

这将为窗口中的每个按钮单击添加一个处理程序.你可能想给你的 StackPanel 一个名字(比如,stackPanel1")并且只为那个容器做:

That'll add a handler for every button click in the window. You might want to give your StackPanel a name (like, "stackPanel1") and do it just for that container:

stackPanel1.AddHandler(Button.ClickEvent, new RoutedEventHandler( button_Click));

这篇关于在 WPF 中,我可以像在 Javascript/Jquery 中一样将相同的点击处理程序一次附加到多个按钮吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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