標籤:des style blog http color java 使用 os
首先自訂事件支援事件路由,需要使用 RegisterRoutedEvent 方法註冊 RoutedEvent
C#文法
public static RoutedEvent RegisterRoutedEvent(string name,RoutingStrategy routingStrategy,Type handlerType,Type ownerType)
參數
-
name
-
類型:System.String 路由事件的名稱。該名稱在所有者類型中必須是唯一的,並且不能為 null 或Null 字元串。
-
routingStrategy
-
類型:System.Windows.RoutingStrategy 作為枚舉值的事件的路由策略。
-
handlerType
-
類型:System.Type 事件處理常式的類型。該類型必須為委託類型,並且不能為 null。
-
ownerType
-
類型:System.Type 路由事件的所有者類類型。該類型不能為 null。
下面我們通過樣本展示自訂路由事件:
先看下xaml檔案,我們可以看到button中並沒有click事件
<Window x:Class="簡單自訂路由事件.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Button Content="擷取時間" Height="29" HorizontalAlignment="Left" Margin="192,170,0,0" Name="button1" VerticalAlignment="Top" Width="100" /> <TextBox Height="58" HorizontalAlignment="Left" Margin="89,80,0,0" Name="textBox1" VerticalAlignment="Top" Width="339" /> <Label Content="自訂路由事件示範" Height="38" HorizontalAlignment="Left" Margin="141,26,0,0" Name="label1" VerticalAlignment="Top" Width="208" FontSize="22" Background="BlanchedAlmond" /> </Grid></Window>
後台代碼簡單展示:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace 簡單自訂路由事件{ /// <summary> /// MainWindow.xaml 的互動邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.button1.AddHandler(Button.ClickEvent,//處理的事件 new RoutedEventHandler(RoutedEvent)); //事件委託 this.MEvent += new RoutedEventHandler(MainWindow_MEvent); } void MainWindow_MEvent(object sender, RoutedEventArgs e) { this.textBox1.Text = System.DateTime.Now.ToString(); } private static readonly RoutedEvent MyEvent = EventManager.RegisterRoutedEvent("Event",//路由事件的名稱 RoutingStrategy.Direct,//事件的路由策略 typeof(RoutedEvent), //事件處理常式的類型。該類型必須為委託類型 typeof(RoutedEventArgs));//路由事件的所有者類類型 //事件訪問器,進行事件提供添加和移除。 public event RoutedEventHandler MEvent { add { AddHandler(MyEvent, value); } remove { RemoveHandler(MyEvent, value); } } void RoutedEvent(object o, RoutedEventArgs e) { //關聯路由事件 RoutedEventArgs args = new RoutedEventArgs(MyEvent); this.RaiseEvent(args); } }}
效果展示:
上面詳細的說明建自訂路由事件的基本原理的原理,我們可以通過這樣的方式來實現自己的路由事件,這樣的代碼移致性很高,我們可以需要的時候直接移植.