设置 .Top 属性,删除 Anchor 属性
我在设计时对一些控件使用了 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我尝试重现您所描述的问题,但无法完全匹配。不过,以下示例可能会帮助您解决我怀疑您遇到的问题。
(我的雇主屏蔽了 SO 的图像托管 i.imgur.com。如果您在查看屏幕截图时遇到任何问题,请告诉我。)
下面的简单表单包含一个锚定在所有四个侧面的组框到它的父窗体。
单击该按钮时,将执行以下代码:
这会导致组框重新定位,如下所示:
但请注意,锚定仍然受到尊重:
我怀疑您正在寻找这样的效果:当您调整控件大小时,除了控件的顶部位置之外,没有任何内容发生变化。不幸的是,在这种情况下,设置
Top
属性会重新定位控件而不是调整其大小。不过,您可以使用
SetBounds()
方法完成大小调整。在下面的示例中,我使用其现有边界调整了锚定控件的大小,并添加了新的顶部。请注意,我没有采取任何措施来避免非法的负高度,而您可能应该这样做。这会导致调整大小和重新定位的控件,之后继续遵守其锚定:
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.
When the button is clicked, the following code executes:
Which results in the group box relocated like so:
Note, however, that anchoring is still honored:
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.This results in a resized and relocated control that continues to honor its anchoring afterward: