【发布时间】:2010-01-13 19:11:06
【问题描述】:
我想对 WPF Canvas 组件执行矩形命中测试,以获取与 Rectangle 框架元素重叠的控件。我找到了 Silverlight 的 VisualTreeHelper.FindElementsInHostCoordinates 方法,但显然它在 WPF 中不可用。
实现此类功能的最佳方法是什么?
【问题讨论】:
标签: c# wpf silverlight hittest visualtreehelper
我想对 WPF Canvas 组件执行矩形命中测试,以获取与 Rectangle 框架元素重叠的控件。我找到了 Silverlight 的 VisualTreeHelper.FindElementsInHostCoordinates 方法,但显然它在 WPF 中不可用。
实现此类功能的最佳方法是什么?
【问题讨论】:
标签: c# wpf silverlight hittest visualtreehelper
最接近的等价物是VisualTreeHelper.HitTest。它的工作方式与 Silverlight 的 FindElementsInHostCoordinates 明显不同,但您应该能够根据需要使用它。
【讨论】:
假设您在 Silverlight 中有这样的电话
var result = VisualTreeHelper.FindElementsInHostCoordinates(myPoint, myUIElement);
那么这个 WPF 代码应该有一个等效的result
var result = new List<DependencyObject>();
//changed from external edits, because VisualHit is
//only a DependencyObject and may not be a UIElement
//this could cause exceptions or may not be compiling at all
//simply filter the result for class UIElement and
//cast it to IEnumerable<UIElement> if you need
//the very exact same result including type
VisualTreeHelper.HitTest(
myUiElement,
null,
new HitTestResultCallback(
(HitTestResult hit)=>{
result.Add(hit.VisualHit);
return HitTestResultBehavior.Continue;
}),
new PointHitTestParameters(myPoint));
在您的特殊情况下,您可能希望使用 GeometryHitTestParameters 而不是 PointHitTestParameters 进行 Rect-Test。
【讨论】: