Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Wpf 如何获取元素在UserControl中的位置_Wpf - Fatal编程技术网

Wpf 如何获取元素在UserControl中的位置

Wpf 如何获取元素在UserControl中的位置,wpf,Wpf,我有一个用户控件: <UserControl d:DesignHeight="100" d:DesignWidth="200" ...> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="100" /> <ColumnDefinition Width="100" /> </Grid

我有一个用户控件:

<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>
但是有人能告诉我如何获得myUserControl1.leftEllipse的位置吗?
当myUserControl1应用旋转变换时,myUserControl1.leftEllipse的位置会改变,不是吗?

在不公开生成的leftEllipse字段的情况下,您可以向UserControl添加一个方法,将变换对象从椭圆的坐标返回到祖先元素的坐标,例如

public GeneralTransform LeftEllipseTransform(UIElement e)
{
    return leftEllipse.TransformToAncestor(e);
}
然后,您可以在主窗口中这样调用它:

var p = myUserControl1.LeftEllipseTransform(this).Transform(new Point());
您也可以使用TranslatePoint,而不是TransformToAncestor或TransformToVisual

public Point GetLeftEllipsePosition(Point p, UIElement e)
{
    return leftEllipse.TranslatePoint(p, e);
}
在主窗口中:

<Window ...>
    <Canvas Name="canvas1">
        <my:MyUserControl x:Name="myUserControl1" Width="200" Height="100" Canvas.Top="100" Canvas.Left="100" />
    </Canvas>
</Window>
var p = myUserControl1.GetLeftEllipsePosition(new Point(), this);
或用于椭圆的中心,而不是其左上角:

var p = myUserControl1.GetLeftEllipsePosition(new Point(25, 25), this);

在WPF中,通常不管理控件的位置和大小,这是由布局系统自动完成的。你到底想实现什么?我想知道它的一些部分的坐标位置,以便动态计算它们与另一点的距离。非常感谢你的回答。你的两种方法我都试过了。它们都很好用!你帮了我一个大忙。再次感谢你。
var p = myUserControl1.GetLeftEllipsePosition(new Point(25, 25), this);