共用方式為


HOW TO:使用幾何當做參數進行點擊測試

更新:2007 年 11 月

本範例示範如何使用 Geometry 做為點擊測試 (Hit Test) 參數,在視覺化物件上執行點擊測試。

範例

下列範例顯示如何使用 GeometryHitTestParameters,為 HitTest 方法設定點擊測試。傳遞至 OnMouseDown 方法的 Point 值可用來建立 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();
    }
}

GeometryHitTestResultIntersectionDetail 屬性會提供將 Geometry 當成點擊測試參數之點擊測試的相關結果資訊。下圖顯示點擊測試幾何圖形 (藍色圓形) 和目標視覺化物件所呈現內容 (紅色正方形) 之間的關係。

點擊測試幾何圖形和目標視覺化物件之間的交集

在點擊測試中使用之 IntersectionDetail 的圖表

下列範例顯示如何在使用 Geometry 當做點擊測試參數時實作點擊測試回呼 (Callback)。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;
    }
}
注意事項:

當交集詳細資料是 Empty 時,就不應該呼叫 HitTestResult 回呼。

請參閱

工作

HOW TO:對 Visual 中的幾何進行點擊測試

概念

視覺分層中的點擊測試