WPF 鼠标按下事件

WPF MouseDown Event

我有一个如下所示的可视化树:

一个Border,包含一个ScrollViewer,其中包含一个TexBlock.

ScrollViewerBorder的space的100%,TextBlock不一定占[=42的100% =] 的 ScrollViewer 取决于用户如何配置它。

我想在用户单击 Border 中的任意位置时捕获 MouseDown 事件。当我为 BorderScrollViewer 注册 MouseDown 事件时,不会调用回调。当我向 TextBlock 注册一个 MouseDown 事件时,回调确实被调用,但当然只在 TextBlock 的可点击区域而不是 [=11= 的整个区域].

我的一个想法是创建某种顶级元素,它将覆盖整个控件,将其可见性设置为隐藏,然后从中获取 MouseDown

有什么建议吗?如果这个问题有什么不清楚的地方,请告诉我,我会解决的。

显示每个请求的示例代码

// Need to know when a user clicks on anything inside of the border, but the 
// because there are items above it, the mouse event doesn't get invoked.
Border border = new Border();
ScrollViewer viewer = new ScrollViewer();
TextBlock textBlock = new TextBlock();

border.Content = viewer;
viewer.Child = textBlock;

您可以在 Border 上注册 PreviewMouseDown 活动。如果单击包含元素,它也会触发。

private void Border_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
  var clickedElement = e.OriginalSource;
}

另一种方法(虽然不是那么干净的 IMO)但如果您需要一些自定义行为,它可能会很有用......也许 :)

我们创建自定义滚动查看器,然后使用它代替标准滚动查看器,我们的自定义控件只会将其鼠标按下事件传播到它的父级(此示例过于简单,因此不适合在当前状态生产).

public class CustomScrollViewer : ScrollViewer
{
    protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        ((e.Source as FrameworkElement).Parent as UIElement).RaiseEvent(e);
    }
}

为像我这样不熟悉 PreviewMouseDown 方法的人提供的一些信息 - 它使用 路由策略 称为 隧道(从上到下)与冒泡(从下到上)

相反