gpt4 book ai didi

c# - WPF: Canvas 吞噬 MouseDownEvent?

转载 作者:太空宇宙 更新时间:2023-11-03 13:43:34 25 4
gpt4 key购买 nike

谁能给我解释一下为什么在这个简单的例子中 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");
}
}
}

点击 Canvas 时的输出是

ScrollViewer_PreviewMouseDown
Canvas_PreviewMouseDown
Canvas_MouseDown

为什么省略了ScrollViewer_MouseDown?我已经调查过 this article但是那里给出的解决方案没有帮助(或者我做错了)。

最佳答案

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

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

输出:

ScrollViewer_PreviewMouseDown
Canvas_PreviewMouseDown
Canvas_MouseDown
ScrollViewer_MouseDown

关于c# - WPF: Canvas 吞噬 MouseDownEvent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16100027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com