2008-11-10 116 views
7

如何獲取兩個無關的控件來引發相同的自定義事件?到目前爲止,我看到的所有例子都有一個事件定義在一個控件中,我應該採取不同的方法嗎?WPF自定義路由事件問題

例如,我想從一個按鈕和一個文本框的OnFocus處理程序中引發一個自定義冒泡事件。

回答

8

首先讓我說你的問題沒有說明你不想使用現有的UIElement.GotFocusEvent,但我會假設你知道它並且有你不使用它的理由。

您可以隨時在靜態類上註冊一個自定義事件,並將其提升到任意位置。 Keyboard class會處理所有事件(例如Keyboard.KeyDownEvent)。

public static class RoutedEventUtility 
{ 
    public static readonly RoutedEvent MyCustomEvent = EventManager.RegisterRoutedEvent("MyCustomEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(RoutedEventUtility)); 
} 

您像舉辦其他RoutedEvent一樣提升事件。

RoutedEventArgs args = new RoutedEventArgs(RoutedEventUtility.MyCustomEvent); 
RaiseEvent(args); 

如果您希望另一個班級將該活動作爲公共字段擁有,那麼您需要添加一個所有者。

public class MyCustomControl : Control 
{ 
    public static readonly RoutedEvent MyCustomEvent = RoutedEventUtility.MyCustomEvent.AddOwner(typeof(MyCustomControl)); 
} 
+0

謝謝。對不起,關於UIElement.GotFocusEvent是正確的假設。 – MJS 2008-11-10 20:22:00