问题
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