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

Answers


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

Need Your Help

Restrain form to the working area of the screen - better solution

vb.net forms screen movement

I have a working code but when moving form to the screen bounds I sometimes get form flickering. Doesn't look good.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.