WPF用户控件HitTest

3

我有以下用户控件:一个点和它的名称:

<UserControl x:Class="ShapeTester.StopPoint"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     mc:Ignorable="d" 
     d:DesignHeight="25" d:DesignWidth="100">

   <StackPanel>
      <Ellipse Stroke="DarkBlue" Fill="LightBlue" Height="10" Width="10"/>
      <TextBlock Text="Eiffel Tower"/>        
  </StackPanel>
</UserControl>

这很酷。

现在,我有一个面板,在其中我需要恢复我用鼠标点击的停止点:

public partial class StopsPanel : UserControl
{
    private List<StopPoint> hitList = new List<StopPoint>();
    private EllipseGeometry hitArea = new EllipseGeometry();

    public StopsPanel()
    {
        InitializeComponent();
        Initialize();
    }

    private void Initialize()
    {
        foreach (StopPoint point in StopsCanvas.Children)
        {
            point.Background = Brushes.LightBlue;
        }
    }

    private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        // Initialization:
        Initialize();
        // Get mouse click point:
        Point pt = e.GetPosition(StopsCanvas);
        // Define hit-testing area:
        hitArea = new EllipseGeometry(pt, 1.0, 1.0);
        hitList.Clear();
        // Call HitTest method:
        VisualTreeHelper.HitTest(StopsCanvas, null,
        new HitTestResultCallback(HitTestCallback),
        new GeometryHitTestParameters(hitArea));
        if (hitList.Count > 0)
        {
            foreach (StopPoint point in hitList)
            {
                // Change rectangle fill color if it is hit:
                point.Background = Brushes.LightCoral;
            }
            MessageBox.Show(string.Format(
                "You hit {0} StopPoint(s)", hitList.Count));
        }
    }

    public HitTestResultBehavior HitTestCallback(HitTestResult result)
    {
        if (result.VisualHit is StopPoint)
        {
            //
            //-------- NEVER ENTER HERE!!! :(
            //

            // Retrieve the results of the hit test.
            IntersectionDetail intersectionDetail =
            ((GeometryHitTestResult)result).IntersectionDetail;
            switch (intersectionDetail)
            {
                case IntersectionDetail.FullyContains:
                // Add the hit test result to the list:
                    hitList.Add((StopPoint)result.VisualHit);
                    return HitTestResultBehavior.Continue;
                case IntersectionDetail.Intersects:
                // Set the behavior to return visuals at all z-order levels:
                    return HitTestResultBehavior.Continue;
                case IntersectionDetail.FullyInside:
                // Set the behavior to return visuals at all z-order levels:
                    return HitTestResultBehavior.Continue;
                default:
                    return HitTestResultBehavior.Stop;
            }
        }
        else
        {
            return HitTestResultBehavior.Continue;
        }
    }
}

因此,正如您所看到的,HitTest从未将UserControl(StopPoint)本身识别为其组件TextBlockEllipse甚至Border)。由于我将业务对象与StopPoint元素关联,因此在鼠标单击时需要获取它,而不是其组成部分。
有没有办法做到这一点?
编辑:
使用筛选器(现在,它根本不会进入HitTestCallback):
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace ShapeTester
{
    /// <summary>
    /// Interaction logic for StopsPanel.xaml
    /// </summary>
    public partial class StopsPanel : UserControl
    {
        private List<StopPoint> hitList = new List<StopPoint>();
        private EllipseGeometry hitArea = new EllipseGeometry();

        public StopsPanel()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            foreach (StopPoint point in StopsCanvas.Children)
            {
                point.Background = Brushes.LightBlue;
            }
        }

        private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Initialization:
            Initialize();
            // Get mouse click point:
            Point pt = e.GetPosition(StopsCanvas);
            // Define hit-testing area:
            hitArea = new EllipseGeometry(pt, 1.0, 1.0);
            hitList.Clear();
            // Call HitTest method:
            VisualTreeHelper.HitTest(StopsCanvas, 
                new HitTestFilterCallback(MyHitTestFilter),
                new HitTestResultCallback(HitTestCallback),
                new GeometryHitTestParameters(hitArea));

            if (hitList.Count > 0)
            {
                foreach (StopPoint point in hitList)
                {
                    // Change rectangle fill color if it is hit:
                    point.Background = Brushes.LightCoral;
                }
                MessageBox.Show(string.Format(
                    "You hit {0} StopPoint(s)", hitList.Count));
            }
        }

        public HitTestResultBehavior HitTestCallback(HitTestResult result)
        {
            if (result.VisualHit is StopPoint)
            {
                //
                //-------- NEVER ENTER HERE!!! :(
                //

                // Retrieve the results of the hit test.
                IntersectionDetail intersectionDetail =
                ((GeometryHitTestResult)result).IntersectionDetail;
                switch (intersectionDetail)
                {
                    case IntersectionDetail.FullyContains:
                    // Add the hit test result to the list:
                        hitList.Add((StopPoint)result.VisualHit);
                        return HitTestResultBehavior.Continue;
                    case IntersectionDetail.Intersects:
                    // Set the behavior to return visuals at all z-order levels:
                        return HitTestResultBehavior.Continue;
                    case IntersectionDetail.FullyInside:
                    // Set the behavior to return visuals at all z-order levels:
                        return HitTestResultBehavior.Continue;
                    default:
                        return HitTestResultBehavior.Stop;
                }
            }
            else
            {
                return HitTestResultBehavior.Continue;
            }
        }

        // Filter the hit test values for each object in the enumeration.
        public HitTestFilterBehavior MyHitTestFilter(DependencyObject o)
        {
            // Test for the object value you want to filter.
            if (o.GetType() == typeof(StopPoint))
            {
                // Visual object's descendants are 
                // NOT part of hit test results enumeration.
                return HitTestFilterBehavior.ContinueSkipChildren;
            }
            else
            {
                // Visual object is part of hit test results enumeration.
                return HitTestFilterBehavior.Continue;
            }
        }
    }
}

你尝试过添加HitTestFilterCallback并在StopPoint上返回ContinueSkipChildren吗?我看到你目前将过滤器回调传递为null。 - Bubblewrap
@Bubblewrap:嗯...你是什么意思?... - serhio
VisualTreeHelper.HitTest的第二个参数,您可以指定一个HitTestFilterCallback。请参见此处:http://msdn.microsoft.com/en-us/library/ms752097.aspx#using_a_hit_test_filter_callback - Bubblewrap
@Bubblewrap:不起作用。我添加了下面的方法: - serhio
3个回答

6

我想写一篇解释,但我已经找到了一个不错的:

https://dev59.com/wk_Ta4cB1Zd3GeqPB488#7162443

要点是:

你的 UserControl.HitTestCore() 遵循默认实现,可能会返回 NULL,这将导致 UC 被跳过而不是传递给 resultCallback。

默认行为不是 bug。这是一个不明显但聪明的设计 - 总的来说,你的控件没有可视化内容,它只是一些具有形状的子项的容器,因此通常 UC 没有被设置为 hittestable 并且不能干扰遍历路径。你可能认为这是一个缺点,因为 UC 的简洁性可能会受益于其 hittestable。然而,简洁并不是目标 - 速度才是。事实上,这是一个重要的特性,因为它确实减少了树遍历器必须执行实际交叉的项目数量!

因此 - 要么实现 HitTestCore 并返回非空内容,要么对 UserControl 的子项进行 hittest,并在获得适当的结果但等于其子项时使用 VisualTreeHelper.GetParent 直到你走到所需的 UserControl。


3
您可以使用VisualTreeHelper来查找父级停止点:
var element = result.VisualHit;
while(element != null && !(element is StopPoint))
    element = VisualTreeHelper.GetParent(element);

if(element == null) return;

0

你能不能不给点添加鼠标点击事件监听器,只需将发送者转换为StopPoint,一切都会很好?不需要额外的命中测试代码。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接