WPF UIElement.IsHitTestVisible=false;仍然返回点击? [英] WPF UIElement.IsHitTestVisible=false; still returning hits?
问题描述
我正在从 FrameworkElement 派生一个控件以用作 VisualCollection 的容器,因为我正在使用 DrawingVisuals(创建游戏地图)进行大量自定义渲染.
I'm deriving a control from FrameworkElement to use as a container for a VisualCollection, as I'm doing a lot of custom rendering using DrawingVisuals (creating a game map).
我有几个不同的容器实例,它们相互叠加,我只希望命中测试影响当前可见的层,所以我尝试做明显的事情,并设置 .IsHitTestVisible=false,根据到 MSDN 应该防止任何子元素作为命中结果返回.
I've got a couple different instances of my container layered on top of each other, and I only want hit testing to affect the layer currently visible, so I tried doing the obvious, and set .IsHitTestVisible=false, which according to MSDN should prevent any child elements being returned as hit results.
但是,我仍然在设置为 .IsHitTestVisible=false 的容器上返回命中.我已经尝试了我能想到的所有其他方法,包括折叠、隐藏、禁用、0 不透明度,但似乎没有什么能从命中测试中消除.
However, I am still getting hits returned on the containers that are set .IsHitTestVisible=false. I've tried everything else I can think of, Collapsed, Hidden, Disabled, 0 Opacity, nothing seems to take it out of the hit testing.
推荐答案
我认为这是一个错误.我使用 Reflector 来了解为什么 HitTest 方法返回不可见的项目,我发现没有检查可见性.
I think it's a bug. I used Reflector to understand why the HitTest method returns invisible items and I have found that there is no check for visibility.
我的解决方案是使用带过滤器的重载 HitTest:
My solution is to use overload HitTest with filter:
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));
希望对你有帮助
这篇关于WPF UIElement.IsHitTestVisible=false;仍然返回点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!