2010-06-24 173 views
1

我目前有一個用戶控件,其中包含具有特定X,Y座標的項目,並且這些點必須位於哪些範圍內有限制。在這種情況下,這些位置是0> X> 40和0> Y> 80(40×80)。我主持這些項目的控件是動態的,但具有基於窗口大小的特定長寬比。我需要將這些X & Y座標轉換爲用戶控件中的相對位置。任何幫助極大apprecaited!提前致謝!如果它很重要/有幫助,我使用Silverlight。翻譯X,Y座標

回答

4

您可以使用GeneralTransform來確定UIElement相對於容器的位置。這裏有一個片段:

/// <summary> 
    /// Gets the position of the specified element's top left corner, relative to the specified container. 
    /// </summary> 
    /// <param name="element"></param> 
    /// <param name="container"></param> 
    public static Point GetPosition(UIElement element, UIElement container) 
    { 
     if (element == null) 
      throw new ArgumentNullException("element"); 
     if (container == null) 
      throw new ArgumentNullException("container"); 
     var gt = element.TransformToVisual(container); 
     var position = gt.Transform(new Point(0, 0)); 
     return position; 
    } 

乾杯,亞歷克斯

爲空[編輯]其實,檢查 「集裝箱」 是不必要的 - TransformToVisual也將接受null作爲參數。 另一個問題:TransformToVisual將拋出一個ArgumentException例如當「元素」不可見時,當前不在可視樹等中。等等。 不幸的是,我找不到一種方法來確定TransformToVisual是否會在實際調用「元素」之前拋出該異常。所以我簡單地將對TransformToVisual的調用封裝在try-catch塊中,吞併了ArgumentException,因爲無論如何IMHO都是無用的。