我目前正在与我被困在一个问题C#WPF自定义路由事件进行实验。 这就是我想要做的:我想火从我的主窗口,它通过一个StackPanel到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>