C#Anchor属性似乎不起作用

时间:2009-10-21 10:47:00

标签: c# winforms forms anchor formborderstyle

我在表单中添加了一些控件并更改了Anchor属性我希望它如何工作,但是当我在运行时调整窗体大小时,控件保持在同一个位置。

例如,我在表单的右下角有两个按钮 - 它们在表单上,​​没有容器或类似的东西。 Anchor = Bottom,Right。 FormBorderStyle =大小。但是当我在运行时拖动调整窗体大小时,按钮不会移动。

我错过了什么吗?

c#2005

9 个答案:

答案 0 :(得分:10)

另一种可能性是您不小心将按钮放在表单上。而是将它们放在某个容器中(例如,panel,tableLayoutPanel等),并且此容器没有将其锚定或对接值设置为正确。

为了绝对确定你应该看看designer.cs并检查你的按钮是否通过this.Controls.Add()函数直接添加到表单中,或者是否添加到任何其他Controls-List中(例如{ {1}})。

答案 1 :(得分:4)

此外,如果您设置了自动尺寸属性,则会造成麻烦。

答案 2 :(得分:4)

我知道这是一篇旧帖子,但无论如何我都想尝试做出贡献。

我的问题是,当父面板的尺寸发生变化时,我添加到面板中的表单并没有自动调整其大小。

问题是我这样做了:

form.WindowState = FormWindowState.Maximized; // <-- source of the problem
form.AutoSize = true; //this causes the form to grow only. Don't set it if you want to resize automatically using AnchorStyles, as I did below.
form.FormBorderStyle = FormBorderStyle.Sizable; //I think this is not necessary to solve the problem, but I have left it there just in case :-)
panel1.Controls.Add(form);
form.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                    | System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
form.Dock = DockStyle.Fill; //this provides the initial size adjust to parent' size.
form.Visible = true;

要解决这个问题,我只是评论了第一行//form.WindowState = FormWindowState.Maximized;,一切都像魅力一样。

答案 3 :(得分:3)

什么是Dock属性设置为?这可以否定锚属性。

答案 4 :(得分:1)

我在VS11 Beta中遇到同样的问题。我经常使用锚点并且它总是正常工作,但现在我无法理解它们发生了什么,不仅仅是 - 码头填充也不起作用! (不使用自动尺寸或底座属性)

P.S。 (40分钟后) 现在它看起来像我发现了问题:我有PictureBox的Resize事件监听器,我在onResize处理程序中为新的图片框大小创建了新的Image。当我删除新的图像创建时,一切正常!

现在我使用SizeChanged事件,并在此事件处理程序中创建新图像。所以我认为在Resize完成之前我不应该更改发件人对象。

答案 5 :(得分:0)

我遇到了同样的问题。

情况:

TableLayoutPanel,其中一行设为autosize。在这一行中锚定Right,Bottom不起作用。 删除autoSize并将其置于固定高度解决了问题,如user428955所述。

答案 6 :(得分:0)

我的问题非常简单,我的所有控件锚属性都已正确设置并包含在面板内。
但我忘了将锚样式设置到容器面板,因此容器面板没有展开根据我想要的形式边框...在设置容器面板的锚属性后,一切都按预期工作。

答案 7 :(得分:0)

如果您的表单可本地化,请检查是否用其他语言更改了锚点/停靠点。

答案 8 :(得分:0)

我也有类似的问题。我发现这是因为我要在form_load上调整表单大小。可以通过在调整表单大小时临时停靠在顶部/左侧来绕过

    private void ResizeFromDesigntimeToRunTime()
    {
        var volatileControls = this.Controls.Cast<Control>().Where(control => (control.Anchor | AnchorStyles.Bottom | AnchorStyles.Right) != AnchorStyles.None).ToList();

        var anchorPairing = volatileControls.ToDictionary(control => control, control => control.Anchor);

        foreach (var control in volatileControls)
            control.Anchor = AnchorStyles.Left | AnchorStyles.Top; //Temporarily reset all controls with an anchor including right or bottom, so that these aren't automatically resized when we adjust form dimensions.

        this.Height = SomeHeight;
        this.Width = SomeWidth;

        foreach (var pair in anchorPairing)
            pair.Key.Anchor = pair.Value;
    }