WPF 用户控件命中测试

发布于 2024-09-19 23:14:55 字数 7375 浏览 7 评论 0原文

我有以下用户控件:一个点及其名称:

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

这很酷。

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

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),而是它的组件(TextBlock椭圆甚至边框)。
当我将业务对象关联到 StopPoint 元素时,我需要在 MouseHitting 时获取它,而不是其组合元素。

有办法做到吗?

编辑:

使用过滤器(现在,它根本不进入 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;
            }
        }
    }
}

I have the following user control: a dot and its name:

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

This is cool.

Now, I have a panel, in witch I need to recuperate my StopPoints that I hit with the Mouse:

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

So, as you can see, the problem that the HitTest never identifies an UserControl(StopPoint) as it is, but rather its components(TextBlock, Ellipse or even Border).
As I associate the business object to the StopPoint element, I need to obtain it when MouseHitting, and not its composing elements.

Is there a way to do it?

EDIT:

Using filter (now, it does not enter at all in the 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;
            }
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

羁拥 2024-09-26 23:14:55

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

https://stackoverflow.com/a/7162443/717732

要点是:

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

默认行为不是错误。这是一个不明显、聪明的设计 - 总而言之,您的控件没有视觉效果,它只是一些具有形状的孩子的容器,因此通常在 UC 中没有必要进行可点击测试并弄乱步行路径。您可能会将其视为一个缺点,因为可命中的 UC 可以使您的代码更加简洁。然而,这里的目标不是简洁,而是速度。事实上,这是一个重要的功能,因为它确实减少了树木漫步者必须执行实际交叉的项目数量!

因此,要么实现 HitTestCore 并返回非空值,要么对 UserControl 的子级进行 hittest,然后当获得正确结果但等于其子级时,使用 VisualTreeHelper.GetParent 直到找到所需的 UserControl。

I wanted to write an explanation, but I've already found a decent one:

https://stackoverflow.com/a/7162443/717732

The point is:

Your UserControl.HitTestCore() is left to the default implementation that probaly returns NULL, that this causes the UC to be skipped instead of be passed to the resultCallback.

The default behaviour is not a bug. This is a not obvious, clever design - all in all, your control has no visuals, it is only container for some children who have the shapes, so generally there's no point in the UC to be hittestable and to clutter the walking path. You may see it as a shortcoming, because the brevity of your code could benefit from the UC being hittestable. However, not the brevity is the goal here - it is the speed. In fact this is an important feature, because it really reduces the amount of items on which the treewalker must perform the actual intersections!

So - either implement the HitTestCore and return something non-null, or hittest for the UserControl's children instead, and then when having a proper result but equal to its child, use the VisualTreeHelper.GetParent until you walk upto the UserControl you wanted.

看春风乍起 2024-09-26 23:14:55

您可以使用 VisualTreeHelper 来查找父停止点:

var element = result.VisualHit;
while(element != null && !(element is StopPoint))
    element = VisualTreeHelper.GetParent(element);

if(element == null) return;

You can use VisualTreeHelper to find the parent stop point:

var element = result.VisualHit;
while(element != null && !(element is StopPoint))
    element = VisualTreeHelper.GetParent(element);

if(element == null) return;
一城柳絮吹成雪 2024-09-26 23:14:55

您是否可以不向这些点添加鼠标单击事件侦听器,而只需将发送者强制转换为 StopPoint 就可以了?不需要额外的命中测试代码。

Could you not add mouse click events listeners to the points, and just cast the sender to StopPoint and it would be all good? No need for the extra hit testing code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文