-->

处理隧道定制路由事件(Handle tunneled custom routed event)

2019-09-19 03:07发布

我目前正在与我被困在一个问题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>

Answer 1:

好吧,我想通了由自己:虽然我喜欢一千倍在MSDN描述,明确指出阅读:

隧道:首先,在元素树的根事件处理程序被调用。 然后,路由事件通过沿所述路线连续的子元素,朝也就是路由事件源( 即提出的路由事件的元件 )的节点元件行进的路线 。 [...]

我的一个隧道路由事件的第一个想法是:我火从主窗口中的事件,它穿过的StackPanel到按钮元素。 而是:你必须从按钮启动它已经-那么它开始于根元素(主窗口),并通过控制层到触发事件摆在首位的按钮元素去。

我所做的是:我从主窗口触发事件,因此不能去别的地方



Answer 2:

该登记似乎并不正确:

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

您需要添加public event ReoutedEventHandler MyRoutedEvent你这里注册的类。 这应该是无静态类实例级别的处理程序。 我没有看到它在你的代码。

您需要需要在主窗口是这样的:

public event RoutedEventHandler MyRoutedEvent;

这里参见MSDN的例子。



文章来源: Handle tunneled custom routed event