WPF Routed Event, Subscribing to Custom Events

I am trying to get routed events that work with child controls that will manually trigger these events, and they will bubble and be processed at the main grid level. I basically want to do something like this:

<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> 

But when I run my example, I get a null reference in the view structure, the application is never initialized, it fails when trying to load / initialize XAML (InitializeComponent ()). Here is a small file containing the event:

 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; } 

I basically want to copy the behavior of ButtonBase.Click allowing parents to subscribe to any click () buttons for their children. But it doesn't seem to work for anything other than ButtonBase.Click (). That is, when I turn off my custom WpfApplication5:SpecialEvent.Tap="Catcher_Tap" before ButtonBase.Click="Catcher_Tap" , it works. Any ideas why? What makes ButtonBase what I am not doing?

+4
source share
2 answers

After playing a little more, I found that I can do what I need in the code behind the main window, for example:

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

For some reason, specifying it in XAML, like ButtonBase (), does not work, but adding Handler to the code is behind.

+5
source

The code you submit registers a custom event, but it does not register an attached custom event. You will need to explicitly implement the Add*Handler and Remove*Handler methods if you want to use the attached syntax with your event. See the "Defining Your Own Connected Events as Routed Events" section in this MSDN article .

0
source

All Articles