2012-07-04 95 views
1

我目前正在試用C#WPF自定義路由事件我卡在一個問題。 這就是我想要做的:我想從我的主窗口中通過一個通過堆棧面板隧道到由Button類派生的自定義控件的自定義路由事件。自定義控件然後處理路由事件。處理隧道自定義路由事件

我的問題是當我觸發事件處理程序從未被調用。

我的代碼:

public partial class MainWindow : Window 
     { 

     public static readonly RoutedEvent MyRoutedEvent = EventManager.RegisterRoutedEvent("MyRoutedEvent", RoutingStrategy.Tunnel, typeof(RoutedEventHandler), typeof(UIElement)); 

     public static void AddMyRoutedEventHandler(DependencyObject d, RoutedEventHandler handler) 
     { 
      UIElement uie = d as UIElement; 
      if (uie != null) 
      { 
       uie.AddHandler(MainWindow.MyRoutedEvent, handler); 
      } 
     } 

     public static void RemoveMyRoutedEventHandler(DependencyObject d, RoutedEventHandler handler) 
     { 
      UIElement uie = d as UIElement; 
      if (uie != null) 
      { 
       uie.RemoveHandler(MainWindow.MyRoutedEvent, handler); 
      } 
     } 


     public MainWindow() 
     { 
      InitializeComponent(); 
     } 

     private void keyClassButton1_MyRoutedEvent(object sender, RoutedEventArgs e) 
     { 
      Console.Write("\nMyRoutedEvent!"); 
     } 

     private void Window_MouseDown(object sender, MouseButtonEventArgs e) 
     { 
      RoutedEventArgs newEventArgs = new RoutedEventArgs(MyRoutedEvent, this); 
      RaiseEvent(newEventArgs); 
     } 
    } 

XAML代碼:

<Window x:Class="RoutedEvent_Test.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:RoutedEvent_Test" 
     Title="MainWindow" Height="350" Width="525" MouseDown="Window_MouseDown"> 
    <Grid> 
     <StackPanel Name="stackPanel1"> 
      <local:KeyClass x:Name="keyClass1" Content="key class button" Height="30" local:MainWindow.MyRoutedEvent="keyClassButton1_MyRoutedEvent"></local:KeyClass> 
     </StackPanel> 
    </Grid> 
</Window> 

回答

0

此登記似乎並不正確:

public static readonly RoutedEvent MyRoutedEvent = EventManager.RegisterRoutedEvent("MyRoutedEvent", RoutingStrategy.Tunnel, typeof(RoutedEventHandler), typeof(UIElement)); 

您需要添加public event ReoutedEventHandler MyRoutedEvent在類因爲你在這裏註冊。這應該是非靜態類實例級別處理程序。我沒有看到你的代碼。

您需要需要在主窗口是這樣的:

public event RoutedEventHandler MyRoutedEvent; 

See MSDN example here.

2

好,我理解了它的自己: 雖然我喜歡一千倍讀它,它顯然在美國MSDN說明:

隧道:最初,元素樹根處的事件處理程序調用了 。 路由事件然後沿着路線經過連續的 子節點,朝向節點元素即 路由事件源(引發路由事件的元素)。 [...]

我的隧道路由事件的第一個想法是:我從主窗口觸發一個事件,它穿過的StackPanel到按鈕元素。 但是INSTEAD: 你必須從按鈕開始它 - 然後它從根元素(主窗口)開始,並通過控制層到首先觸發事件的按鈕元素。

我做的是:我從主窗口中解除了事件,因此無法到達其他地方