windows 防止事件 C# 冒泡

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5944608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:49:27  来源:igfitidea点击:

Prevent Bubbling of Event C#

c#.netwindows

提问by redDragonzz

Suppose I have an event KeyPresssubscribed to by various classes. Assume that Class A also subscribes to KeyPresson the form and Class B also subscribes to KeyPress

假设我有一个KeyPress由各种类订阅的事件。假设 A 类也订阅KeyPress了表单,B 类也订阅了KeyPress

Now I wish that only one of these classes should handle the event fired by the Form in runtime. That is let's say Class A handles first, I have tried using e.Handled = truebut that is not helping in this case.

现在我希望只有这些类中的一个应该在运行时处理由 Form 触发的事件。也就是说,让我们先说 A 类处理,我已经尝试使用,e.Handled = true但在这种情况下没有帮助。

I do not want class B to handle the event fired from the form if class A has handled already, I have a work around currently which involves setting some public flags within A and B, but that is not a good idea from software engineering principle, I want the classes to be as independent of each other as possible but at the same time, should know that an event has already been handled and does not need to be handled again.

如果 A 类已经处理了,我不希望 B 类处理从表单触发的事件,我目前有一个解决方法,涉及在 A 和 B 中设置一些公共标志,但这从软件工程原理来看并不是一个好主意,我希望这些类尽可能相互独立,但同时,应该知道一个事件已经被处理,不需要再次处理。

Is that possible?

那可能吗?

Yes it's possible, need to check for e.Handled == trueand .NET takes care of the rest :-)

是的,这是可能的,需要检查e.Handled == true并且 .NET 会处理其余的 :-)

采纳答案by Kelly Summerlin

You have to check e.Handled inside each event handler like this Gist exampleI created.

您必须在每个事件处理程序中检查 e.Handled,就像我创建的这个Gist 示例一样。

Basically each handler needs to check for e.Handled == true and return if already handled. The Handled property does not short-circuit the event handling, it only pushes down the arguments to each subscribed event.

基本上每个处理程序都需要检查 e.Handled == true 并且如果已经处理则返回。Handled 属性不会短路事件处​​理,它只会将参数下推到每个订阅的事件。

In my example, the Form1 class always handles the event first because it is wired up in the Form1 constructor. Thus by setting e.Handled = true in that event and then checking e.Handled == true in the other events, I can just return immediately when e.Handled == true.

在我的示例中,Form1 类总是首先处理事件,因为它连接在 Form1 构造函数中。因此,通过在该事件中设置 e.Handled = true,然后在其他事件中检查 e.Handled == true,我可以在 e.Handled == true 时立即返回。