微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – WPF UIElement.IsHitTestVisible = false;仍然返回命中?

我从FrameworkElement派生一个控件,用作VisualCollection的容器,因为我正在使用DrawingVisuals(创建游戏图)进行大量的自定义渲染.

我有几个不同的我的容器的实例分层在彼此之上,我只想要命中测试影响当前可见的层,所以我尝试做明显的,并设置.IsHitTestVisible = false,根据MSDN应该防止任何子元素作为命中结果返回.

但是,我仍然在设置的容器上返回命中.IsHitTestVisible = false.
我已经尝试过一切我可以想到的,折叠,隐藏,残疾,0不透明度,似乎没有把它从命中测试.

解决方法

我认为这是一个bug.我使用Reflector来了解为什么HitTest方法返回不可见的项目,我发现没有检查可见性.

我的解决方案是使用过滤器的HitTest:

public static HitTestFilterBehavior HitTestFilterInvisible(DependencyObject potentialHitTestTarget)
{
    bool isVisible = false;
    bool isHitTestVisible = false;

    var uiElement = potentialHitTestTarget as UIElement;
    if (uiElement != null)
    {
        isVisible = uiElement.IsVisible;
        if (isVisible)
        {
            isHitTestVisible = uiElement.IsHitTestVisible;
        }
    }
    else
    {
        UIElement3D uiElement3D = potentialHitTestTarget as UIElement3D;
        if (uiElement3D != null)
        {
            isVisible = uiElement3D.IsVisible;
            if (isVisible)
            {
                isHitTestVisible = uiElement3D.IsHitTestVisible;
            }
        }
    }

    if (isVisible)
    {
        return isHitTestVisible ? HitTestFilterBehavior.Continue : HitTestFilterBehavior.ContinueSkipSelf;
    }

    return HitTestFilterBehavior.ContinueSkipSelfAndChildren;
}
...
// usage:

    VisualTreeHelper.HitTest(
        myHitTestReference,HitTestFilterInvisible,hitTestResult =>
        {
            // code to handle element which is visible to the user and enabled for hit testing.
        },new PointHitTestParameters(myHitTestPoint));

我希望它能帮助你

原文地址:https://www.jb51.cc/csharp/95686.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐