1

仍然爬上陡峭的WPF山,痛苦。

我已经定义了一个 UserControl,我的 MainWindow 需要检索来自 UserControl 内部控件的 MouseButtonEventArgs(例如鼠标 e.GetPosition)

在后面的 UserControl 代码中,我完成了注册并引发了冒泡事件。

public static readonly RoutedEvent MyButtonDownEvent = EventManager.RegisterRoutedEvent("MyMouseButtonDown", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));
    public event RoutedEventHandler MyButtonDown {
        add { AddHandler(MyButtonDownEvent, value); }
        remove { RemoveHandler(MyButtonDownEvent, value); }
    }
    private void MyMouseButtonDownHandler(object sender, MouseButtonEventArgs e) {
        RaiseEvent(new RoutedEventArgs(MyButtonDownEvent ));
    }

现在在我的 MainWindow 中,我像这样声明 UserControl:

<local:MyUserControl MouseDown="MyUserControl_MouseDown"/>

后面的代码

private void MyUserControl_MouseDown(object sender, RoutedEventArgs e) 

我从 UserControl 接收事件,但 Args 是 RoutedEventArgs(这是正常的),但我无法访问获取鼠标 e.GetPosition 所需的 MouseButtonEventArgs。

在这种情况下,您会建议什么优雅的解决方案?

4

2 回答 2

1

为什么MouseDownUserControl已经有正常的 MouseDown 事件的情况下定义自己的事件?

无论如何,如果你定义一个事件来使用 a RoutedEventHandler,那么你最终会被 a 卡住也就不足为奇了RoutedEventHandler。你这样声明:

public static readonly RoutedEvent MyButtonDownEvent = EventManager.RegisterRoutedEvent("MyMouseButtonDown", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(MyUserControl));

注意它说的那一点typeof(RoutedEventHandler)

如果我没记错的话,你的代码应该是这样的:

    public static readonly RoutedEvent MyButtonDownEvent =
        EventManager.RegisterRoutedEvent
        ("MyButtonDown",
        RoutingStrategy.Bubble,
        typeof(MouseButtonEventHandler),
        typeof(MyUserControl));

    public event MouseButtonEventHandler MyButtonDown
    {
        add { AddHandler(MyButtonDownEvent, value); }
        remove { RemoveHandler(MyButtonDownEvent, value); }
    }

如何将现有 MouseDown 事件传播到自定义事件的示例:

InitializeComponent();
this.MouseDown += (s, e) => {
    RaiseEvent(new MouseButtonEventArgs(e.MouseDevice, e.Timestamp, e.ChangedButton)
                    { 
                        RoutedEvent = MyButtonDownEvent
                    });
};
于 2011-02-14T19:26:13.327 回答
0

我想我终于明白了(至少我希望如此):

如果我在后面的代码中写:

        public event EventHandler<MouseButtonEventArgs> MyRightButtonDownHandler;
    public void MyRightButtonDown(object sender, MouseButtonEventArgs e) {
        MyRightButtonDownHandler(sender, e);
    }

然后在消费者 (MainWindow) XAML 中:

<local:GlobalDb x:Name="globalDb"  MyRightButtonDownHandler="globalDb_MyRightButtonDownHandler"/>

在后面的消费者代码中:

    private void globalDb_MyRightButtonDownHandler(object sender, MouseButtonEventArgs e) {
        Console.WriteLine("x= " + e.GetPosition(null).X + " y= " + e.GetPosition(null).Y);
    }

请告诉我您是否有更好的解决方案(根据设计策略 - 在我工作的地方建立规则 - 我的应用程序的所有事件处理必须出现在 XAML 中)。

再次感谢您的帮助,

于 2011-02-15T18:39:04.657 回答