# WPF如何得到一个在用户控件内部的元素的坐标位置

<UserControl d:DesignHeight="100" d:DesignWidth="200" ...>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Ellipse Name="leftEllipse" Grid.Column="0" Width="50" Height="50" HorizontalAlignment="Center" VerticalAlignment="Center" Fill="Red" />
<Ellipse Name="rightEllipse" Grid.Column="1" Width="50" Height="50" HorizontalAlignment="Center" VerticalAlignment="Center" Fill="Green" />
</Grid>
</UserControl>

<Window ...>
<Canvas Name="canvas1">
<my:MyUserControl x:Name="myUserControl1" Width="200" Height="100" Canvas.Top="100" Canvas.Left="100" />
</Canvas>
</Window>

double x = Canvas.GetLeft(myUserControl1);

//方法1：

public GeneralTransform LeftEllipseTransform(UIElement e)
{
return leftEllipse.TransformToAncestor(e);
}

var p = myUserControl1.LeftEllipseTransform(canvas1).Transform(new Point());　　//得到左圆的左上角坐标

//方法2：

public Point GetLeftEllipsePosition(Point p, UIElement e)
{
return leftEllipse.TranslatePoint(p, e);
}

var p = myUserControl1.GetLeftEllipsePosition(new Point(), canvas1);　　//得到左圆的左上角坐标

var p = myUserControl1.GetLeftEllipsePosition(new Point(25, 25), canvas1);　　//得到左圆的圆心坐标
posted @ 2018-05-03 10:47 Fixing 阅读(...) 评论(...) 编辑 收藏