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



我有一个具有首选大小的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);
    }
}

Nevermind,如果使用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);
    };

最新更新