2

谁能向我解释为什么在这个简单MouseDown的例子中事件没有达到?ScrollViewer

<Window x:Class="MouseDownTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ScrollViewer Name="scrollViewer" Background="Green" MouseDown="ScrollViewer_MouseDown" PreviewMouseDown="ScrollViewer_PreviewMouseDown">
            <Canvas Name="canvas" Background="Beige" MouseDown="Canvas_MouseDown" PreviewMouseDown="Canvas_PreviewMouseDown">
            </Canvas>
        </ScrollViewer>
    </Grid>
</Window>

后面的代码:

using System;
using System.Windows;
using System.Windows.Input;

namespace MouseDownTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            scrollViewer.AddHandler(MouseDownEvent, new RoutedEventHandler(ScrollViewer_Test));
        }

        private void ScrollViewer_Test(object sender, RoutedEventArgs routedEventArgs)
        {
            Console.WriteLine("ScrollViewer_Test");
        }

        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("Canvas_MouseDown");
        }

        private void Canvas_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("Canvas_PreviewMouseDown");
        }

        private void ScrollViewer_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("ScrollViewer_MouseDown");
        }

        private void ScrollViewer_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            Console.WriteLine("ScrollViewer_PreviewMouseDown");
        }
    }
}

单击画布时的输出是

ScrollViewer_PreviewMouseDown
Canvas_PreviewMouseDown
Canvas_MouseDown

为什么会ScrollViewer_MouseDown被省略?我已经查看了这篇文章,但那里给出的解决方案没有帮助(或者我做错了)。

4

1 回答 1

1

您可能需要设置Focusable="False"允许ScrollViewer鼠标事件通过

 <ScrollViewer Name="scrollViewer" Focusable="False" Background="Green" />

输出:

ScrollViewer_PreviewMouseDown
Canvas_PreviewMouseDown
Canvas_MouseDown
ScrollViewer_MouseDown
于 2013-04-19T08:27:50.960 回答