面板上的AutoScroll显示不正确的不必要的滚动条

时间:2014-08-25 22:15:17

标签: c# winforms user-interface panel autoscroll

我有一个具有首选大小的winforms用户界面。如果其父表单的大小低于面板PreferredSize,则会自动显示滚动条,因为AutoScroll属性设置为true。如果其父窗体的大小增加,则面板将填充额外的空间,并隐藏滚动条。很简单。

问题在于,即使表单大于PreferredSize,减小表单的大小也会简要显示滚动条,即使它们是不必要的。

以下简单示例再现了该问题。随着表单变小,即使没有满足首选大小限制,滚动条也会随机出现。 (Button仅用于说明问题,实际的UI更复杂。)

使用WPF不是一种选择。

public class Form6 : Form {

    Control panel = new Button { Text = "Button" };

    public Form6() {
        this.Size = new Size(700, 700);

        Panel scrollPanel = new Panel();
        scrollPanel.AutoScroll = true;
        scrollPanel.Dock = DockStyle.Fill;

        scrollPanel.SizeChanged += delegate {
            Size s = scrollPanel.Size;
            int minWidth = 400;
            int minHeight = 400;
            panel.Size = new Size(Math.Max(minWidth, s.Width), Math.Max(minHeight, s.Height));

            // this is a little better, but still will show a scrollbar unnecessarily
            // one side is less but the other side is >=.
            //scrollPanel.AutoScroll = (s.Width < minWidth || s.Height < minHeight);
        };

        scrollPanel.Controls.Add(panel);

        this.Controls.Add(scrollPanel);
    }
}

1 个答案:

答案 0 :(得分:1)

没关系,如果使用的是ClientSize而不是Size,并取消注释AutoScroll行,那么就可以解决问题。我将它留在这里为后代。

    scrollPanel.SizeChanged += delegate {
        //Size s = scrollPanel.Size;
        Size s = scrollPanel.ClientSize;
        int minWidth = 400;
        int minHeight = 400;
        panel.Size = new Size(Math.Max(minWidth, s.Width), Math.Max(minHeight, s.Height));

        // this is a little better, but still will show a scrollbar unnecessarily
        // one side is less but the other side is >=.
        scrollPanel.AutoScroll = (s.Width < minWidth || s.Height < minHeight);
    };