2012-07-27 65 views
4

我正在嘗試使用子控件來處理路由事件,這些子控件將手動觸發這些事件,並且它們會在主網格級別處於起泡狀態並進行處理。基本上,我想要做這樣的事情:WPF路由事件,訂閱自定義事件

<Grid Name="Root" WpfApplication5:SpecialEvent.Tap="Catcher_Tap"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="40" /> 
     <RowDefinition Height="40" /> 
     <RowDefinition Height="*" /> 
    </Grid.RowDefinitions> 
    <WpfApplication5:UserControl2 Grid.Row="0" x:Name="Catcher" /> 
    <WpfApplication5:UserControl1 Grid.Row="1" /> 
    <Frame Grid.Row="2" Source="Page1.xaml" /> 
</Grid> 

但是當我運行我的例子,我得到的演示框架空引用,應用程序從不初始化時,它失敗時,它試圖加載/初始化XAML(的InitializeComponent())。下面是一個包含該事件的小檔案:

public class SpecialEvent 
{ 
    public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
     "Tap", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(UserControl1)); 

    // Provide CLR accessors for the event 
    public event RoutedEventHandler Tap; 
} 

我基本上是想複製的ButtonBase.Click如何讓家長訂閱任何按鈕,點擊自己的孩子()方法的行爲。但是,這似乎並不適用於ButtonBase.Click()。也就是說,當我將我的自定義WpfApplication5:SpecialEvent.Tap="Catcher_Tap"切換爲ButtonBase.Click="Catcher_Tap"時,它可以工作。任何想法爲什麼? ButtonBase在做什麼,我沒做什麼?

回答

5

周圍一些玩後,我發現,這是可能做到什麼,我需要在代碼中像這樣在主窗口的後面:

public MainWindow() 
    { 
     InitializeComponent(); 
     Root.AddHandler(SpecialEvent.TapEvent, new RoutedEventHandler(Catcher_Tap)); 
    } 

出於某種原因,在XAML指定它,你會對於ButtonBase()不起作用,但在後面的代碼中加入Handler

0

您提供的代碼註冊了一個自定義事件,但是,它沒有註冊附帶的自定義事件。如果您想在事件中使用附加語法,則必須明確實施Add*HandlerRemove*Handler方法。請參閱this MSDN article上的「將您自己的附加事件定義爲路由事件」部分。