在 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);
我希望能够在伪代码中执行类似的操作:
this.button*.Click += new System.EventHandler(this.button_Click);
在 Javascript 中可能有类似的东西在 WPF 中吗?
I have multiple buttons instead of doing
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);
In Javascript it is possible is there something like that in WPF ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 WPF 中,
Button.Click
是一个路由事件,这意味着事件将在可视化树中向上路由,直到被处理。这意味着您可以在 XAML 中添加一个事件处理程序,如下所示:现在所有按钮都将为其 Click 事件共享一个处理程序 (button_Click)。
这是在同一父容器中的一组控件之间处理同一事件的简单方法。如果您想从代码中执行相同的操作,可以使用 AddHandler 方法,如下所示:
这将为窗口中的每个按钮单击添加一个处理程序。您可能想要为您的 StackPanel 指定一个名称(例如“stackPanel1”)并仅为该容器执行此操作:
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:Now all the buttons will share a single handler (button_Click) for their Click event.
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:
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:
不要制作
button1
、button2
等,而是制作一个按钮列表。然后您可以编写:
从 XAML 您可以将单击处理程序附加到按钮的父级,如下所示(我使用 StackPanel 作为示例):
这有效,因为按钮 Click 事件是一个冒泡路由事件。
Instead of making
button1
,button2
etc, make a List of buttons.Then you can write:
From XAML you can attach the click handler to the parent of the buttons something like this (I use a StackPanel as an example):
This works because the buttons Click event is a bubbling routed event.
您可以使用 Linq To VisualTree找到 Window / UserControl 中的所有按钮,然后迭代此列表以添加事件处理程序。
我认为这已经是您所能得到的最简洁的了!
You could use Linq To VisualTree to locate all the buttons in your Window / UserControl, then iterate over this list adding your event handler.
I think that is about as concise as you are going to get it!