设置 .Top 属性,删除 Anchor 属性

发布于 2024-09-16 17:44:30 字数 91 浏览 3 评论 0原文

我在设计时对一些控件使用了 Anchor 属性。 但是当我在运行时更改这些控件的 .Top 属性时,它似乎弄乱了 Anchor 属性并且不再遵守它。 怎么了?如何修复?

I have used Anchor property for some of my controls at design time.
but when I change the .Top property of those controls at run time, it seems that it is messing with the Anchor property and does not honor it anymore.
what is happening? how to fix?

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

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

发布评论

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

评论(1

傲娇萝莉攻 2024-09-23 17:44:30

我尝试重现您所描述的问题,但无法完全匹配。不过,以下示例可能会帮助您解决我怀疑您遇到的问题。

(我的雇主屏蔽了 SO 的图像托管 i.imgur.com。如果您在查看屏幕截图时遇到任何问题,请告诉我。)

下面的简单表单包含一个锚定在所有四个侧面的组框到它的父窗体。

Screenshot 01

单击该按钮时,将执行以下代码:

groupBox1.Top = 0;

这会导致组框重新定位,如下所示:

Screenshot 02

但请注意,锚定仍然受到尊重:

Screenshot 03

我怀疑您正在寻找这样的效果:当您调整控件大小时,除了控件的顶部位置之外,没有任何内容发生变化。不幸的是,在这种情况下,设置 Top 属性会重新定位控件而不是调整其大小。

不过,您可以使用 SetBounds() 方法完成大小调整。在下面的示例中,我使用其现有边界调整了锚定控件的大小,并添加了新的顶部。请注意,我没有采取任何措施来避免非法的负高度,而您可能应该这样做。

        int newtop = 0; // the new top bound
groupBox1.SetBounds(
        groupBox1.Left,
        newtop,
        groupBox1.Width,
        groupBox1.Height + groupBox1.Top - newtop);

这会导致调整大小和重新定位的控件,之后继续遵守其锚定:

Screenshot 04

I tried to reproduce the problem you describe, but was not able to match it exactly. The following example, however, may help you resolve the issue I suspect you are having.

(My employer blocks i.imgur.com, the image host for SO. If you have any problems viewing the screenshots, let me know.)

The following simple form contains a group box anchored on all four sides to its parent form.

Screenshot 01

When the button is clicked, the following code executes:

groupBox1.Top = 0;

Which results in the group box relocated like so:

Screenshot 02

Note, however, that anchoring is still honored:

Screenshot 03

I suspect you are looking for the effect that nothing except the top location of the control changes when you resize the control. Unfortunately, in this case, setting the Top property relocates the control rather than resize it.

You can accomplish resizing using the SetBounds() method, however. In the example below, I resize the anchored control, with a new top, using its existing bounds. Note that I don't take any measures to avoid illegal negative heights, which you probably should.

        int newtop = 0; // the new top bound
groupBox1.SetBounds(
        groupBox1.Left,
        newtop,
        groupBox1.Width,
        groupBox1.Height + groupBox1.Top - newtop);

This results in a resized and relocated control that continues to honor its anchoring afterward:

Screenshot 04

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