We know that WPF has a flexible Layout mode. For the coordinates of a widget, the elements in the canvas are the simplest. We can directly obtain them using the getleft () and gettop methods, however, the relative positions of elements in other layout panels and those in different layout panels are a headache for us. In fact, there is a simple method. I don't know if you have found any.
1. Obtain the position of the element relative to the parent control.
Using the vector visualtreehelper. getoffset (visual) method, it returns the offset of the visual in its parent control. Then you can convert the returned vector object to a point object.
2. Obtain the position of an element relative to the ancestor control or descendant control.
Use the generaltransform transformtoancetor (visual ancetor) method of the element and generaltransform transform (visual descendent). The returned element is relative to generaltransform mygeneraltransform of the ancestor or descendant, and then use point thepoint = mygeneraltransform. the thepoint object obtained by transform (new point (0, 0) is the value to be searched.
3. Obtain the relative position of any two elements.
There are two methods:
If the element is visual, you can use the generaltransform transformtovisual (visual) method of the element, and then obtain thepoint from generaltransform with the method at above.
If the element is a uielement, it is simpler. You can use the element's translatepoint (point PT, uielement relativeto) to obtain the value of the PT point on the element relative to relativeto, only when Pt is (0, 0) can we obtain the relative position of the (0, 0) point on the element, that is, the relative position of the element.