AutoScroll on Panel Shows Incorrect Unnecessary Scrollbars

若如初见. 提交于 2019-12-12 01:44:25

问题


I have a winforms user-interface that has a preferred size. If the size of its parent form is below the panel's PreferredSize, then scrollbars are automatically displayed because the AutoScroll property is set to true. If the size of its parent form is increased, then the panel fills the additional space, and the scrollbars are hidden. Simple enough.

The problem is that even when the form is larger than the PreferredSize, decreasing the size of the form will briefly show the scrollbars, even though they are unnecessary.

The following simple example reproduces the problem. As the form is made smaller, the scrollbars will randomly appear even though the preferred size limit hasn't been met. (A Button is used to illustrate the problem only, the actual UI is more complicated).

Using WPF is not an option.

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:


Nevermind, if ClientSize is used instead of Size, and uncomment the AutoScroll line, then it solves the problem. I'll leave it here for posterity.

    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);
    };


来源:https://stackoverflow.com/questions/25495183/autoscroll-on-panel-shows-incorrect-unnecessary-scrollbars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!