2016-01-17 47 views
0

我有一個畫布。當我點擊它時,我會得到鼠標的座標並向上(添加一個孩子)在那裏擁有自定義控件(一個簡單的圓圈的拇指)。 在屏幕上,邏輯上,添加時將左上角作爲參考。我希望將拇指的中心放在我點擊的地方(見圖片,紅色的星星=我點擊的地方)。在WinRT中獲取UIElement的大小

enter image description here

做什麼,我需要獲得拇指的實際寬度和高度,然後計算出準確的coordonate到地方,用戶點擊拇指的中心。有沒有更好的辦法 ? 在WPF中,我使用了這段代碼,但它在WinRT中不起作用。

//Circle in thumb 
Ellipse Bdr = this.GetTemplateChild("Forme") as Ellipse; 
DependencyObject dobj = VisualTreeHelper.GetParent(Bdr); 
Vector ParentPosition = VisualTreeHelper.GetOffset((Visual)VisualTreeHelper.GetParent(dobj)); 
Vector BdrPosition = VisualTreeHelper.GetOffset((Visual)dobj); 
return new Point((Position.X+BdrPosition.X) + Bdr.ActualWidth /2,(Position.Y+ ParentPosition.Y) + Bdr.ActualHeight/2); 

你能幫我嗎?謝謝 !

回答

1

ActualHeightActualWidth屬性保持0,直到FrameworkElement未加載。另一方面,如果您在ControlTemplate中確定了尺寸Ellipse,則可以在OnApplyTemplate()上獲得尺寸。您可以使用代理將高度和寬度傳遞給容器Page。即

ThumbControl

public class ThumbControl : Control 
{ 
    public IThumbSize thumbSize; 
    public ThumbControl() 
    { 
     this.DefaultStyleKey = typeof(ThumbControl); 
    } 

    protected override void OnApplyTemplate() 
    { 
     base.OnApplyTemplate(); 
     Ellipse child = this.GetTemplateChild("circle") as Ellipse; 
     if (thumbSize != null) 
      thumbSize.SizeMeasured(child.Width, child.Height); 
    } 
} 

ThumbControl的伴奏

<Style TargetType="local:ThumbControl"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="local:ThumbControl"> 
        <Ellipse x:Name="circle" 
          Fill="Blue" 
          Height="50" 
          Width="50"></Ellipse> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

IThumb接口

public interface IThumbSize 
{ 
    void SizeMeasured(double width, double height); 
} 

ContainerPage.xaml

<Grid Background="Black"> 
    <Canvas x:Name="rootCanvas" 
      Background="Transparent" 
      PointerReleased="rootCanvas_PointerReleased"></Canvas> 
</Grid> 

ContainerPage.xaml.cs

public sealed partial class ContainerPage: Page, IThumbSize 
{ 
    ThumbControl thumbControl = new ThumbControl(); 
    Point touchPoint = new Point(); 
    public ContainerPage() 
    { 
     this.InitializeComponent(); 
     thumbControl.thumbSize = this; 
    } 

    private void rootCanvas_PointerReleased(object sender, PointerRoutedEventArgs e) 
    { 
     PointerPoint pt = e.GetCurrentPoint(rootCanvas); 
     touchPoint.X = pt.Position.X; 
     touchPoint.Y = pt.Position.Y; 
     if (!rootCanvas.Children.Contains(thumbControl)) 
      rootCanvas.Children.Add(thumbControl); 
     Canvas.SetLeft(thumbControl, touchPoint.X - (thumbControl.ActualWidth/2)); 
     Canvas.SetTop(thumbControl, touchPoint.Y - (thumbControl.ActualHeight/2)); 
    } 

    public void SizeMeasured(double width, double height) 
    { 
     Canvas.SetLeft(thumbControl, touchPoint.X - (width/2)); 
     Canvas.SetTop(thumbControl, touchPoint.Y - (height/2)); 
    } 
} 

希望它幫助。