I'm currently experimenting with C# WPF custom routed events i got stuck at a problem. This is what i want to do: I want to fire a custom routed event from my main window which tunnels through a stackpanel to a custom control derived by the Button class. The custom control then handles the routed event.
My problem is when i fire the event the handler is never been called.
My code:
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 code:
<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>