WPF中如何进行相对定位?

发布于 2024-07-05 19:04:28 字数 321 浏览 5 评论 0原文

如何在 WPF 中相对定位元素? 标准模型是对所有内容使用布局管理器,但是如果您想仅根据其他元素的位置来定位元素(例如在 Canvas 上)怎么办?

例如,您可能希望将一个元素(例如按钮)附加到另一个元素(可能是面板)的一侧,而与该面板的位置或布局无关。 使用过工程工具(SolidWorks、AutoCad 等)的任何人都熟悉这种相对定位。

将所有内容强制放入布局管理器(不同的 WPF 面板)对于某些情况没有多大意义,在这种情况下,您不关心元素由某些父容器维护,并且不希望其他子容器受到父容器更改的影响。彼此的布局/外观。 WPF 是否以任何方式支持这种相对定位模型?

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?

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无妨# 2024-07-12 19:04:28

您可以在画布上放置一个堆栈面板,水平对齐,然后将两个按钮放在那里,而不是将按钮直接放在画布上(如您的示例中所示)。

像这样:

<Canvas>
  <StackPanel Canvas.Left="100" Canvas.Top="100" Orientation="Horizontal">
    <Button>Button 1</Button><Button>Button 2</Button>
  </StackPanel>
</Canvas>

alt text

我认为当您使用超过 1 个布局时它非常灵活在一个表单中,您可以创建几乎任何您想要的配置。

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>

alt text

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.

北城半夏 2024-07-12 19:04:28

好问题。 据我所知,我们需要有一个不同的自定义面板才能获得此功能。 由于 WPF 基于视觉层次结构,因此平台中的元素无法拥有这种扁平结构。

但是这里有一个技巧可以做到这一点。
将元素放置在相同位置并使用 RenderTransform.TranslateTransform 给出相对位移。 这样,您的 TranslateTransfrom 的 X 和 Y 将始终与其他元素相关。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文