我在我的WinForm中有一个FlowLayoutPanel,其中的图像是动态添加的。我希望竖直滚动条始终位于底部,显示最后添加的图像。我应该如何做呢?
我已经设置了以下属性:
AutoScroll = true Flow Direction = Top Down
Wrap Content = False
我已经设置了以下属性:
AutoScroll = true Flow Direction = Top Down
Wrap Content = False
可滚动的容器控件,比如FlowLayoutPanel,会自动将拥有焦点的控件保持在视图中。但是PictureBox是特殊的,它无法接收焦点。因此,您需要通过显式要求FLP使添加的控件可见,使用其ScrollControlIntoView()方法来进行帮助。像这样:
var pic = new PictureBox();
//...
flowLayoutPanel1.Controls.Add(pic);
flowLayoutPanel1.ScrollControlIntoView(pic);
这种方法的强大之处在于它适用于您应用于FLP的任何布局设置。您还可以尝试调整AutoScrollPosition属性,但这更难正确地完成:
flowLayoutPanel1.AutoScrollPosition = new Point(
pic.Right - flowLayoutPanel1.AutoScrollPosition.X,
pic.Bottom - flowLayoutPanel1.AutoScrollPosition.Y);
flowLayoutPanel.ScrollControlIntoView(Control_To_Add); // Control_To_Add is the control we want to scroll to
Button TempButton = new Button();
TempButton.Width = _Panel.ClientRectangle.Width - 6; // Make the last control in the _Panel
flowLayoutPanel.Controls.Add(TempButton); // We add this TempButton so we can scroll to the bottom of the _Panel.Controls
flowLayoutPanel.ScrollControlIntoView(b); // We scroll to TempButton at the bottom of the _Panel.Controls
flowLayoutPanel.Controls.Remove(b); // We remove TempButton
b.Dispose(); // clean up
强制 FlowLayoutPanel 滚动并显示所有控件。
代码更正:flowLayoutPanel.ScrollControlIntoView(Control_To_Add); // Control_To_Add is the control we want to scroll to
Button TempButton = new Button();
TempButton.Width = _Panel.ClientRectangle.Width - 6; // Make the last control in the _Panel
flowLayoutPanel.Controls.Add(TempButton); // We add this TempButton so we can scroll to the bottom of the _Panel.Controls
flowLayoutPanel.ScrollControlIntoView(TempButton); // We scroll to TempButton at the bottom of the _Panel.Controls
flowLayoutPanel.Controls.Remove(TempButton); // We remove TempButton
b.Dispose(); // clean up
这是正确的方式:
MyControl uct = new MyControl();
uct.Parent = flowLayoutPanel;
this.ActiveControl = uct;
if (flowLayoutPanel.VerticalScroll.Visible)
{
flowLayoutPanel.ScrollControlIntoView(uct);
}