我想让一个Panel
垂直滚动,但不包括水平方向(因此AutoScroll
无法使用,因为子控件会超出左边缘)。
那么该如何实现呢?
mypanel.AutoScroll = false;
mypanel.HorizontalScroll.Enabled = false;
mypanel.HorizontalScroll.Visible = false;
mypanel.HorizontalScroll.Maximum = 0;
mypanel.AutoScroll = true;
假设您正在使用winforms,那么默认的面板组件不能为您提供禁用水平滚动组件的方法。解决此问题的一种方法是禁用自动滚动并自己添加滚动条:
ScrollBar vScrollBar1 = new VScrollBar();
vScrollBar1.Dock = DockStyle.Right;
vScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };
panel1.Controls.Add(vScrollBar1);
更详细的讨论请点击此处。
VScrollBar
组件来完成它? - Seth CarnegieVerticalScroll.Value
属性与 Scroll
事件同步。更新了代码。请注意,为了获得滚动效果,面板底部应该有一些元素溢出(即应该有一些不可见的元素可以滚动到)。 - Teoman SoygulAutoScroll
实际上是解决方案!
您只需将AutoScrollMargin
设置为0, 1000
或类似的值,然后使用它向下滚动并在那里添加按钮和项目!
Panel
有一个AutoScroll
属性。只需将该属性设置为True
,面板在需要时会自动添加滚动条。
panelUserInput.SuspendLayout();
panelUserInput.Controls.Clear();
panelUserInput.AutoScroll = false;
panelUserInput.VerticalScroll.Visible = false;
// here you'd be adding controls
int x = 20, y = 20, height = 0;
for (int inx = 0; inx < numControls; inx++ )
{
// this example uses textbox control
TextBox txt = new TextBox();
txt.Location = new System.Drawing.Point(x, y);
// add whatever details you need for this control
// before adding it to the panel
panelUserInput.Controls.Add(txt);
height = y + txt.Height;
y += 25;
}
if (height > panelUserInput.Height)
{
VScrollBar bar = new VScrollBar();
bar.Dock = DockStyle.Right;
bar.Scroll += (sender, e) => { panelUserInput.VerticalScroll.Value = bar.Value; };
bar.Top = 0;
bar.Left = panelUserInput.Width - bar.Width;
bar.Height = panelUserInput.Height;
bar.Visible = true;
panelUserInput.Controls.Add(bar);
}
panelUserInput.ResumeLayout();
// then update the form
this.PerformLayout();
三个步骤:
1- 将AutoScroll属性设置为true
2- 在Form的load()方法中添加以下内容:
my Panel Vertical Scroll Maximum = 10000
3- 在我的面板控件添加(item)之后添加以下内容: Invalidate();
完成!
在Kamgman的答案基础上进行补充,这确实有效。
假设我们将标签作为子控件添加到面板中:
AutoScroll
设置为True,将AutoSize
设置为False。AutoSize
设置为true。如果您愿意,可以为其设置MinimumSize
以使其至少在水平方向上保持其“形状”。Anchor
设置为仅Top。删除其左锚定。这样可以确保标签仅在垂直方向上滚动而不是水平方向上滚动。如果您选择这种方法,则无需添加隐藏水平滚动条的行。
如果您正在使用System.ComponentModel.ComponentResourceManager.ApplyResources
从.resx
文件中加载它,而不是从.Designer.cs
文件中加载,则可能会更好。因为在我的情况下,每当我对此特定表单进行编辑时,我都会失去Designer.cs
文件中的更改。但这将取决于您的项目设置方式。
<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>
Panel
上没有名为Scrollbars
的属性,也没有在 Intellisense 中显示。我看到其他人谈论过它,所以我认为它是存在的,但我可能做错了什么。我在这一行代码中得到了这个错误:panel1.Scrollbars = ScrollBars.Vertical;
-'System.Windows.Forms.Panel'
不包含 'Scrollbars' 的定义,并且找不到接受类型为 'System.Windows.Forms.Panel' 的第一个参数的扩展方法 'Scrollbars' (是否缺少使用指令或程序集引用?) - Seth Carnegie