在`BorderedCanvas`上调用的`RaiseEvent`不会调用事件处理程序

时间:2018-03-01 10:48:51

标签: c# wpf

我有以下C#类:

class MouseWheelEventListenerViewManager : ReactViewManager
{

    public override void OnDropViewInstance(ThemedReactContext reactContext, BorderedCanvas canvas)
    {
        base.OnDropViewInstance(reactContext, canvas);
        RemoveListeners(canvas);
    }

    protected override BorderedCanvas CreateViewInstance(ThemedReactContext reactContext)
    {
        var borderedCanvas = base.CreateViewInstance(reactContext);
        AddListeners(borderedCanvas);
        return borderedCanvas;
    }

    protected void AddListeners(BorderedCanvas borderedCanvas)
    {
        Console.Write("In AddListeners");
        borderedCanvas.PreviewMouseWheel += PreviewMouseWheel;
    }

    protected void RemoveListeners(BorderedCanvas borderedCanvas)
    {
        borderedCanvas.PreviewMouseWheel -= PreviewMouseWheel;
    }

    protected static void PreviewMouseWheel(object sender, MouseWheelEventArgs e)
    {
        Console.Write("Added PreviewMouseWheel");
        if (!e.Handled)
        {
            e.Handled = true;

            var eventArg =
                new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta)
                {
                    RoutedEvent = UIElement.MouseWheelEvent,
                    Source = sender
                };

            UIElement parent = VisualTreeHelper.GetParent((UIElement)sender) as UIElement;
            parent?.RaiseEvent(eventArg);
        }
    }

}

此代码实现了它在我的应用程序中应该做的事情(允许在ScrollViewer上滚动),所以我认为它是正确的。但是,我不知道如何测试它。

我添加了此测试,该测试应检查MouseWheelEvent是否标记为handled

    [Test]
    public void MouseWheelEvent_is_marked_as_handled()
    {

        var invoked = new AutoResetEvent(false);
        var mouseWheelEventListenerViewManager = new MouseWheelEventListenerViewManager();

        BorderedCanvas canvas = mouseWheelEventListenerViewManager.CreateView(new ThemedReactContext(new ReactContext()));

        MouseWheelEventArgs me = new MouseWheelEventArgs(InputManager.Current.PrimaryMouseDevice, 10, 10)
        {
            RoutedEvent = Mouse.MouseWheelEvent
        };
        canvas.RaiseEvent(me);

        Assert.True(invoked.WaitOne(new TimeSpan(0, 0, 0, 20)));
        invoked.Set();
        Assert.IsTrue(me.Handled);
   }

此测试在Assert.IsTrue(me.Handled)处失败,并且仅在控制台上打印:

In AddListeners

通常情况下,应该打印出来:

In AddListeners
Added PreviewMouseWheel

这意味着即使调用PreviewMouseWheel,也不会从测试中调用方法AddListeners,这意味着canvas.PreviewMouseWheel已初始化。

知道为什么会这样吗?

0 个答案:

没有答案