For example there is a user control like this:
<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>
Here is the main window:
<Window ...> <Canvas Name="canvas1"> <my:MyUserControl x:Name="myUserControl1" Width="200" Height="100" Canvas.Top="100" Canvas.Left="100" /> </Canvas> </Window>
We know that the coordinate position of the user control itself can be obtained by the following methods:
double x = Canvas.GetLeft(myUserControl1);
So how to get the coordinates of the elements inside the user control? Be aware that when the user control itself applies a transformation (eg: RotateTransform), the coordinates of its internal elements will change.
There are two ways to solve this problem:
//method 1:
Write the method in the user control:
public GeneralTransform LeftEllipseTransform(UIElement e) { return leftEllipse.TransformToAncestor(e); }
In the main window call:
var p = myUserControl1.LeftEllipseTransform(canvas1).Transform( new Point()); //Get the coordinates of the upper left corner of the left circle
//Method 2:
Write the method in the user control:
public Point GetLeftEllipsePosition(Point p, UIElement e) { return leftEllipse.TranslatePoint(p, e); }
In the main window call:
var p = myUserControl1.GetLeftEllipsePosition( new Point(), canvas1); //Get the coordinates of the upper left corner of the left circle
Or, if you want to get the center position of the left circle, call it like this:
var p = myUserControl1.GetLeftEllipsePosition( new Point( 25 , 25 ), canvas1); //Get the coordinates of the center of the left circle