gpt4 book ai didi

c# - 使 VisualTreeHelper.HitTest 在单元测试中工作?

转载 作者:行者123 更新时间:2023-11-30 18:33:46 32 4
gpt4 key购买 nike

我想在某些形状上使用 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));
}

最佳答案

HitTest 基于元素的呈现,因此您应该测量和排列形状。例如

shape.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
shape.Arrange(new Rect(shape.DesiredSize));

或者您可以只使用 FillContains几何的方法。例如

var result = shape.Data.FillContains(ToPoint(target));

关于c# - 使 VisualTreeHelper.HitTest 在单元测试中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17032884/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com