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

标签 c# wpf nunit hittest

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

相关文章:

c# - ASP.NET 安全身份验证和授权的最佳实践

c# - 程序集 'SomeAssembly, uses ' System.Web.Mvc,Version=4.0.0.0,其版本高于引用的程序集 'System.Web.Mvc,Version 3.0.0.0

c# - 更改组合框选择时,IValueConverter不更新Datagrid

wpf - 为什么在 Windows 中缩放 WPF 应用程序时会看到像素?

c# - 单元测试抛出 "System.NullReferenceException",使用 Moq 和 Nunit

c# - 如何设置 NUnit 来运行我的项目的单元测试?

c# - 如何在Unity中访问TextMeshProUGUI

c# - 重置密码时出现 "Invalid token"错误,ASP.Net Identity 2.2.0

c# - WPF 如何在鼠标事件上绘制圆圈

c# - 执行 javascript 时,Watin 集成测试因 System.UnauthorizedAccessException 而失败