开发者

The current co-ordinates of a given WPF Control

Given a System.Windows.Controls.Control, how can I find the top left and bottom right c开发者_如何学Pythonorners of the control, in pixels? Also, how can I then set the said corners? I want to be resizing or moving the control arbitrarily based on where it currently is. I'm in C#.

Thanks.


You can get the location of a Visual relative to another Visual by using TransformToVisual. For example, if child is your control and parent is a parent such as the Window:

 var point = child.TransformToVisual(parent).Transform(new Point(0, 0));

You can use ActualHeight and ActualWidth to get the size, and you can work out the bottom and right by adding those to the location.

The position of the control is set by the WPF Layout System, so you can't set the position in all cases. If you want to be able to change it, make your control a child of a Canvas, and set the attached Canvas.Top and Canvas.Left properties:

Canvas.SetLeft(child, 123);
Canvas.SetTop(child, 456);

Update: As Anvaka points out, there are a few ways to set the position of an element even if it isn't inside a Canvas. One is to set the Margin. The element will be shifted down by Margin.Top and right by Margin.Left (although it will also be made smaller). You can even set the components of the margin to negative values to have the element overflow its container on any side.

The other way is with RenderTransform or LayoutTransform. From the docs, "LayoutTransform ignores TranslateTransform operations", but you could still use a RenderTransform:

child.RenderTransform = new TranslateTransform(left, top);

If you are designing the UI to allow elements to be explicitly positioned, though, you will probably find it easier to add a Canvas to the parent and add the movable elements to the Canvas.


This depends on the container your control is in. I assume that you have the control in a Canvas, if you want to move it freely.

In this post you see how you get the position. With and Height you can get by the corresponding properties of the control. In this post you see a snippet of code to move elements.

You can do this also with other containers than Canvas but this will be more tricky because you have to work with indirect values (margin).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜