wpf 你如何在WPF中进行相对定位?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/158175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you do relative positioning in WPF?
提问by Marchy
How can you relatively position elements in WPF? The standard model is to use layout managers for everything, but what if you want to position elements (on a Canvas, for example) simply based on the position of other elements?
如何在 WPF 中相对定位元素?标准模型是对所有内容都使用布局管理器,但是如果您只想根据其他元素的位置来定位元素(例如在 Canvas 上)怎么办?
For example, you may want one element (say a button) to be attached the side of another (perhaps a panel) independent of the position or layout of that panel. Anyone that's worked with engineering tools (SolidWorks, AutoCad, etc.) is familiar with this sort of relative positioning.
例如,您可能希望将一个元素(例如按钮)附加到另一个(可能是面板)的一侧,而与该面板的位置或布局无关。任何使用过工程工具(SolidWorks、AutoCad 等)的人都熟悉这种相对定位。
Forcing everything into layout managers (the different WPF Panels) does not make much sense for certain scenarios, where you don't care that elements are maintained by some parent container and you do not want the other children to be affected by a change in the layout/appearance of each other. Does WPF support this relative positioning model in any way?
将所有内容强制放入布局管理器(不同的 WPF 面板)在某些情况下没有多大意义,在这种情况下,您不关心元素是否由某个父容器维护,并且您不希望其他子项受到更改的影响彼此的布局/外观。WPF 是否以任何方式支持这种相对定位模型?
回答by Dave Arkell
Instead of putting (as in your example) a button directly on the canvas, you could put a stackpanel on the canvas, horizontally aligned, and put the two buttons in there.
您可以将一个堆栈面板放在画布上,水平对齐,然后将两个按钮放在那里,而不是(如您的示例中那样)直接在画布上放置按钮。
Like so:
像这样:
<Canvas>
<StackPanel Canvas.Left="100" Canvas.Top="100" Orientation="Horizontal">
<Button>Button 1</Button><Button>Button 2</Button>
</StackPanel>
</Canvas>
I think that it's quite flexible when you use more than 1 layout in a form, and you can create pretty much any configuration you want.
我认为当您在一个表单中使用 1 个以上的布局时它非常灵活,并且您几乎可以创建任何您想要的配置。
回答by Jobi Joy
Good question. As far as I know, we need to have a different custom panel to get this feature. Since WPF is based on Visual Hierarchy there is no way to have this sort of Flat structure for the elements in the platform.
好问题。据我所知,我们需要一个不同的自定义面板来获得这个功能。由于 WPF 基于 Visual Hierarchy,因此无法为平台中的元素提供这种扁平结构。
But Here is a trick to do this.Place your elements in the same position and give relative displacement by using RenderTransform.TranslateTransform. This way your TranslateTransfrom's X and Y will always be relatuve to the other element.
但是这里有一个技巧可以做到这一点。将您的元素放在相同的位置并使用 RenderTransform.TranslateTransform 给出相对位移。这样您的 TranslateTransfrom 的 X 和 Y 将始终与其他元素相关。