Практическое руководство. Проверка нажатия с использованием геометрического объекта в качестве параметра
В этом примере показано, как выполнить проверку попадания для визуального объекта, используя в качестве параметра объект Geometry.
Пример
В этом примере показано, как настроить проверку попадания, используя GeometryHitTestParameters для метода HitTest. Значение Point, передаваемое в метод OnMouseDown
, используется для создания объекта Geometry для расширения диапазона проверки попадания.
// Respond to the mouse button down event by setting up a hit test results callback.
private void OnMouseDown(object sender, MouseButtonEventArgs e)
{
// Retrieve the coordinate of the mouse position.
Point pt = e.GetPosition((UIElement)sender);
// Expand the hit test area by creating a geometry centered on the hit test point.
EllipseGeometry expandedHitTestArea = new EllipseGeometry(pt, 10.0, 10.0);
// Clear the contents of the list used for hit test results.
hitResultsList.Clear();
// Set up a callback to receive the hit test result enumeration.
VisualTreeHelper.HitTest(myControl, null,
new HitTestResultCallback(MyHitTestResultCallback),
new GeometryHitTestParameters(expandedHitTestArea));
// Perform actions on the hit test results list.
if (hitResultsList.Count > 0)
{
ProcessHitTestResultsList();
}
}
' Respond to the mouse button down event by setting up a hit test results callback.
Private Overloads Sub OnMouseDown(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
' Retrieve the coordinate of the mouse position.
Dim pt As Point = e.GetPosition(CType(sender, UIElement))
' Expand the hit test area by creating a geometry centered on the hit test point.
Dim expandedHitTestArea As New EllipseGeometry(pt, 10.0, 10.0)
' Clear the contents of the list used for hit test results.
hitResultsList.Clear()
' Set up a callback to receive the hit test result enumeration.
VisualTreeHelper.HitTest(myControl, Nothing, New HitTestResultCallback(AddressOf MyHitTestResultCallback), New GeometryHitTestParameters(expandedHitTestArea))
' Perform actions on the hit test results list.
If hitResultsList.Count > 0 Then
ProcessHitTestResultsList()
End If
End Sub
Свойство IntersectionDetailGeometryHitTestResult предоставляет информацию о результатах проверки попадания, использующей Geometry в качестве параметра проверки. На следующем рисунке показана связь между геометрическим объектом проверки нажатия (синий круг) и отображенным содержимым целевого визуального объекта (красный квадрат).
В следующем примере показано, как реализовать обратный вызов проверки попадания при использовании Geometry в качестве параметра проверки попадания. Параметр result
приведен к GeometryHitTestResult, чтобы вернуть значение свойства IntersectionDetail. Это значение позволяет определить, находится ли параметр проверки попадания Geometry полностью или частично в отображаемом содержимом целевого объекта проверки попадания. В этом случае пример кода только добавляет результаты проверки попадания в список визуальных объектов, которые полностью содержатся в пределах границ целевого объекта.
// Return the result of the hit test to the callback.
public HitTestResultBehavior MyHitTestResultCallback(HitTestResult result)
{
// Retrieve the results of the hit test.
IntersectionDetail intersectionDetail = ((GeometryHitTestResult)result).IntersectionDetail;
switch (intersectionDetail)
{
case IntersectionDetail.FullyContains:
// Add the hit test result to the list that will be processed after the enumeration.
hitResultsList.Add(result.VisualHit);
return HitTestResultBehavior.Continue;
case IntersectionDetail.Intersects:
// Set the behavior to return visuals at all z-order levels.
return HitTestResultBehavior.Continue;
case IntersectionDetail.FullyInside:
// Set the behavior to return visuals at all z-order levels.
return HitTestResultBehavior.Continue;
default:
return HitTestResultBehavior.Stop;
}
}
' Return the result of the hit test to the callback.
Public Function MyHitTestResultCallback(ByVal result As HitTestResult) As HitTestResultBehavior
' Retrieve the results of the hit test.
Dim intersectionDetail As IntersectionDetail = (CType(result, GeometryHitTestResult)).IntersectionDetail
Select Case intersectionDetail
Case IntersectionDetail.FullyContains
' Add the hit test result to the list that will be processed after the enumeration.
hitResultsList.Add(result.VisualHit)
Return HitTestResultBehavior.Continue
Case IntersectionDetail.Intersects
' Set the behavior to return visuals at all z-order levels.
Return HitTestResultBehavior.Continue
Case IntersectionDetail.FullyInside
' Set the behavior to return visuals at all z-order levels.
Return HitTestResultBehavior.Continue
Case Else
Return HitTestResultBehavior.Stop
End Select
End Function
Примечание.
Обратный вызов HitTestResult не осуществляется, если элемент объединения по пересечению Empty.
См. также
.NET Desktop feedback
Обратная связь
https://aka.ms/ContentUserFeedback.
Ожидается в ближайшее время: в течение 2024 года мы постепенно откажемся от GitHub Issues как механизма обратной связи для контента и заменим его новой системой обратной связи. Дополнительные сведения см. в разделеОтправить и просмотреть отзыв по