我想在某些形状上使用WPF HitTest功能而不在屏幕上显示它们。这可能吗?此代码不能按我预期的方式工作。我如何使这项工作?
[Test, Ignore, RequiresSTA]
public void VerifyFillContains()
{
// make a simple triangle:
var seg1 = new System.Windows.Media.LineSegment(new Point(0.2, 0.1), false);
var seg2 = new System.Windows.Media.LineSegment(new Point(0.3, 0.8), false);
var figure = new PathFigure(new Point(0.7, 0.5), new List<PathSegment>{seg1, seg2}, true);
var sg = new PathGeometry();
sg.Figures.Add(figure);
if (sg.CanFreeze)
sg.Freeze();
// these don't work:
Assert.IsFalse(sg.FillContains(new Point()));
Assert.IsFalse(sg.FillContains(new Point(1.0, 1.0)));
Assert.IsTrue(sg.FillContains(new Point(0.5, 0.5)));
var path = new Path { Data = sg, Fill = Brushes.Black };
path.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
path.Arrange(new Rect(path.DesiredSize));
// and these don't work:
var result = VisualTreeHelper.HitTest(path, new Point(0.0, 0.0));
Assert.IsFalse(result != null && Equals(result.VisualHit, path));
result = VisualTreeHelper.HitTest(path, new Point(1.0, 1.0));
Assert.IsFalse(result != null && Equals(result.VisualHit, path));
result = VisualTreeHelper.HitTest(path, new Point(0.5, 0.5));
Assert.IsTrue(result != null && Equals(result.VisualHit, path));
}
答案 0 :(得分:1)
命中测试基于元素的渲染,因此您应该测量和排列形状。 e.g。
shape.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
shape.Arrange(new Rect(shape.DesiredSize));
或者您可以使用几何的FillContains方法。 e.g。
var result = shape.Data.FillContains(ToPoint(target));
答案 1 :(得分:-1)
我认为您的CreateWpfShapeFromList必须为您的形状的视觉孩子实施AddVisualChild方法。
因为我反映了VisualTreeHelper并且发现HitTest正在使用GetVisualChild,所以请尝试我的解决方案。