Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

c# - WPF: Canvas swallowing MouseDownEvent?

Can anybody please explain to me why theMouseDownevent is not reaching theScrollViewerin this easy example?

<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>

code behind:

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");
        }
    }
}

Output when clicking canvas is

ScrollViewer_PreviewMouseDown
Canvas_PreviewMouseDown
Canvas_MouseDown

Why isScrollViewer_MouseDownbeing omitted? I already looked into this article but the solution given there does not help (or I did it wrong).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will probably need to set Focusable="False" on the ScrollViewer to allow the mouse events to pass though

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

Output:

ScrollViewer_PreviewMouseDown
Canvas_PreviewMouseDown
Canvas_MouseDown
ScrollViewer_MouseDown

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...