在我理解 WPFRoutedEvent處理的程序中,這是它的作業方式嗎?假設
我在. Window_ 我的事件處理程式如下所示:GridButtonGridButton_Click
private void Button_Click(object sender, RoutedEventArgs e)
{
// Do stuff
e.Handled = true;
}
呼叫e.Handled = true;會阻止事件在可視樹中冒泡。
這就是我開始迷路的地方。
- 如果我理解正確,不呼叫
e.Handled = True;可能會導致另一個事件處理程式觸發,Grid或者Window如果他們有一個活動的事件偵聽器Click? - 冒泡是否會自行停止?
- 如果我不停止事件傳播,是否會影響性能?
- 最重要的是,我是否應該默認將事件標記為已處理?
uj5u.com熱心網友回復:
呼叫
e.Handled = True;會阻止事件在可視樹中冒泡。
不,它沒有。它僅向元素樹上的路由上的后續事件處理程式指示之前的另一個事件處理程式已將事件標記為已處理。
如果我理解正確,不呼叫
e.Handled = True;可能會導致另一個事件處理程式觸發,Grid或者Window如果他們有一個活動的事件偵聽器Click?
是的,但這取決于。在某些情況下,控制元件會自動將事件標記為已處理,例如Button,因此在這些情況下,如果其他元素附加了此類事件的處理程式,它們將不會被執行。
將事件
ButtonBase標記MouseLeftButtonDown為在OnMouseLeftButtonDown方法中處理并引發Click事件。因此,OnMouseLeftButtonDown對于繼承自 的控制元件,該事件將永遠不會發生ButtonBase。
此外,在 XAML 中,如果添加事件處理程式,則只有在未處理事件時才會執行它,但. 但是,在代碼隱藏中,您仍然可以添加一個事件處理程式,即使使用 s 上的e.Handled方法并傳遞給引數,也可以執行該處理程式。trueAddHandlerUIElementtruehandledEventsToo
public void AddHandler (System.Windows.RoutedEvent routedEvent, Delegate handler, bool handledEventsToo);
為指定的路由事件添加路由事件處理程式,將處理程式添加到當前元素的處理程式集合中。指定
handledEventsToo為true已被標記為由沿事件路由的另一個元素處理的路由事件呼叫提供的處理程式。
如前所述,這只能在代碼隱藏中實作,它沒有 XAML 語法。
冒泡是否會自行停止?
是的,它停在元素樹的根部,在大多數情況下,例如 a Window。
如果我不停止事件傳播,是否會影響性能?
事件仍將被傳播,這就是路由事件機制的作業方式。當然,如果由于事件被標記為已處理而未呼叫其他處理程式,則不會執行這些行,但這會更改應用程式的功能,這是另一回事。作為一般規則,不要過早優化。如果隨時出現性能問題,請使用分析器分析您的應用程式,獲取可靠且有意義的資料以找到熱點并解決那里的問題。事先優化不太可能成為性能問題的東西沒有必要或好處。
And the most important, should I, by default, mark the event handled?
Again it depends on what you want to achieve. Suppose you have a ListView with lots of items. It shows a scrollbar that can be operated using the mouse wheel. So when you start to scroll the mouse wheel, an event is raised that invokes scrolling the embedded ScrollViewer. In this case, the event is handled automatically. Why? If this ListView was part of a large UI Control with other parent ScrollViewers they would scroll, too, if the event was not handled. Imagine multiple nested controls scrolling all at once, that would be terrible. In other scenarios there may be a need that parent controls also get the event.
This is an excerpt from the documentation on When to Mark Events as Handled:
There is no absolute rule for when you should mark routed events as handled, either as an application author, or as a control author who responds to existing routed events or implements new routed events. For the most part, the concept of "handled" as carried in the routed event's event data should be used as a limited protocol for your own application's responses to the various routed events exposed in WPF APIs as well as for any custom routed events. Another way to consider the "handled" issue is that you should generally mark a routed event handled if your code responded to the routed event in a significant and relatively complete way.
完整的段落讓您更詳細地了解什么是重要且完整的方式,但正如您所見,沒有可以應用的黃金法則,這取決于您的要求和設計。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/422330.html
標籤:
上一篇:在DataGrid中系結資料時,CommandParameter未傳遞給CanExecute(CanExecute引數為空)
