WPF中的VisualTreeHelper.HitTest问题 [英] Problem with VisualTreeHelper.HitTest in WPF

查看:502
本文介绍了WPF中的VisualTreeHelper.HitTest问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Canvas上的一堆UserControl进行命中测试.我不希望HitTest()贯穿视觉树的整个过程,所以我使用FilterCallback来确保仅对UserControl进行命中测试.

I'm trying to hit-test a bunch of UserControls on a Canvas. I don't want the HitTest() to walk the whole way through the visual tree, so I'm using the FilterCallback to make sure I only hit-test the UserControl.

我的问题是UserControl从未命中,应该命中,但没有命中.如果我使用FilterCallback,则返回没有任何结果.如果我让HitTest在视觉树中运行,它将跳过UserControl.

My problem is that the UserControl never hits, it should, but it doesn't. If I use the FilterCallback, I return that it hit nothing. If I let the HitTest run through the visual tree, it skips the UserControl.

以下是一些代码:

<Canvas x:Name="Container">
<UserControl>
   <Grid>
      <Rectangle />
   </Grid>
</UserControl>
<UserControl>
   <Grid>
      <Rectangle />
   </Grid>
</UserControl>
</Canvas>

...
VisualTreeHelper.HitTest(Container, OnFilter, OnResult, myPoint);
...

private void OnResult(DependencyObject o)
{
   //I'll get the Rectangle here, but never the userControl  
}

private void OnFilter(DependencyObject o)
{
   //I will get the UserControl here, but even when I do nothing more than continue, it will not trigger a visualHit.  But the child rectangle will.
}

推荐答案

我遇到了同样的HitTest问题,找不到用户控件.显然,这是设计使然( http://social.msdn.microsoft.com/Forums/zh-CN/wpf/thread/005dad03-c8eb-405f-9567-50653a0e612c ).

I had this same problem of HitTest not finding a user control. Apparently this is by design (http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/005dad03-c8eb-405f-9567-50653a0e612c).

我通过处理用户控件中某些元素的命中情况,然后使用VisualTreeHelper.GetParent方法查找父用户控件来解决此问题.我对WPF还不是很熟悉,所以我不确定使用FrameworkElement.Parent属性是否更好.

I worked around this by handling the hit of some element inside the user control, and then finding the parent user control using the VisualTreeHelper.GetParent method. I'm not very familiar with WPF yet, so I'm not sure if it would be better to use FrameworkElement.Parent property.

但是,这是我的一种方法,该方法是先通过点击测试找到用户控件(或某些必需类型的任何可视父级)后找到用户控件的方法:

However, here is my method for finding the user control (or any visual parent of some required type) after first finding some of its content elements by hit test:

public static T GetVisualParent<T>(this DependencyObject element) where T : DependencyObject
{
    while (element != null && !(element is T))
        element = VisualTreeHelper.GetParent(element);

    return (T)element;
}

这篇关于WPF中的VisualTreeHelper.HitTest问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆