1. 程式人生 > 其它 >WPF學習之--路由事件2

WPF學習之--路由事件2

路由事件是沿著VisualTree傳遞的,VisualTree和LogicalTree的區別就在於LogicalTree的葉子結點是構成使用者介面的控制元件,而VisualTree要連控制元件中的細微結構也要算上。

建自定義路由事件大體可以分為三個步驟:

(1)宣告並註冊路由事件

(2)為路由事件新增CLR事件包裝

(3)建立可以激發路由事件的方法

以下是手動建立一個路由事件,這個事件的用途是報告事件發生的時間。

//事件引數
    class ReportTimeRoutedEventArgs:RoutedEventArgs
    {
        public ReportTimeRoutedEventArgs(RoutedEvent routedEvent, object
source) : base(routedEvent, source) { } public DateTime ClickTime { get; set; } }
using System;
using System.Windows.Controls;
using System.Windows;

namespace MyRoutedEvent
{
    class TimeButton:Button
    {
        //宣告和註冊路由事件\
        public static readonly RoutedEvent ReportTimeRoutedEvent =
            EventManager.RegisterRoutedEvent(
"ReportTime", RoutingStrategy.Bubble, typeof(EventHandler<ReportTimeRoutedEventArgs>), typeof(TimeButton)); //CLR事件包裝 public event RoutedEventHandler ReportTime { add { this.AddHandler(ReportTimeRoutedEvent, value); } remove { this.RemoveHandler(ReportTimeRoutedEvent, value); } }
//激發路由事件,借用Click事件的激發方法 protected override void OnClick() { base.OnClick();//保證Button原有功能正常使用,Click事件被激發 ReportTimeRoutedEventArgs args = new ReportTimeRoutedEventArgs(ReportTimeRoutedEvent, this); args.ClickTime = DateTime.Now; this.RaiseEvent(args);//UIElement及其派生類 } } }
View Code

定義路由事件與定義依賴屬性非常相似,宣告一個由Public static readonly 修飾的RoutedEvent型別欄位,然後使用EventManager類的RegisterRouteEvent方法進行註冊。

第一個引數:路由事件的名稱,和CLR事件包裝器的名稱保持一致。

第二個引數:路由事件的策略。

Bubble,冒泡式;Tunnel,隧道式;Direct,直達式。

第三個引數:用於指定事件處理器的型別。事件處理器的返回型別和引數型別必須和此引數指定的委託保持一致。

第四個引數:用於指明路由事件的宿主是哪個型別。

RoutedEventArgs類

由於所有的WPF事件引數類繼承自RoutedEventArgs,因此任何事件處理程式都可以使用以下屬性。

  • Source:表示LogicalTree上的訊息源頭。
  • OriginalSource:表示VisualTree上的源頭
  • Handled:該屬性允許終止事件的冒泡或隧道過程。
  • RouteEvent:通過事件處理程式為觸發的事件提供RoutedEvent物件。如果同一個事件處理程式處理不同的事件,這一資訊是非常有用的。

WPF事件

重要的事件包括以下幾類:

  • 生命週期事件
  • 滑鼠事件
  • 鍵盤事件
  • 手寫筆事件
  • 多點觸控事件