winforms 设置滚动值后,面板滚动条似乎未滚动

14ifxucb  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(141)

在面板上以编程方式设置滚动值后(在该面板中重新填充控件后),我无法使垂直滚动条显示为滚动。示例:表单打开:

void form_Load(object sender, EventArgs e)
{
    this.Controls.Clear();
    this.Size = new(250, 250);
    Panel panel = new() { AutoScroll = true, Size = new(200, 200), BorderStyle = BorderStyle.FixedSingle, Location = new(5, 5) };
    this.Controls.Add(panel);
    this.Click += this_Click;
}

字符串
结果:


的数据
现在,单击处理程序,我只想清除面板中的内容,并用控件重新填充它,以演示我在更大的上下文中所做的事情:

void this_Click(object sender, EventArgs e)
{
    foreach (Panel panel in Controls.OfType<Panel>())
    {
        Console.WriteLine(panel.VerticalScroll.Value.ToString() + "/" +
            panel.VerticalScroll.Maximum.ToString()); // prints "0/100"
        panel.Controls.Clear();
        for (int i = 0; i < 5; i++)
        {
            Label label = new() {
                AutoSize = false,
                Size = new(175, 100),
                Location = new(5, i * 105),
                BorderStyle = BorderStyle.FixedSingle,
                Text = i.ToString()
            };
            panel.Controls.Add(label);
        }
        panel.VerticalScroll.Value = 200;
        Console.WriteLine(panel.VerticalScroll.Value.ToString() + "/" +
            panel.VerticalScroll.Maximum.ToString()); // prints "0/519"
    }
}


您看到的结果是面板滚动,但滚动条似乎位于顶部位置:



在此之后手动滚动条将其放置在正确的位置:



如何使滚动条显示为在设置值后滚动到实际位置?

xu3bshqb

xu3bshqb1#

根据上面@dr.null的建议,我修改了点击事件,解决了这个问题:

void this_Click(object sender, EventArgs e)
{
    foreach (Panel panel in Controls.OfType<Panel>())
    {
        panel.SuspendLayout(); // addition
        for (int i = panel.Controls.Count - 1; i >= 0; i--)
        { panel.Controls[i].Dispose(); } // replace Clear call
        for (int i = 0; i < 5; i++)
        {
            Label label = new() {
                AutoSize = false,
                Size = new(175, 100),
                Location = new(5, i * 105),
                BorderStyle = BorderStyle.FixedSingle,
                Text = i.ToString()
            };
            panel.Controls.Add(label);
        }
        panel.VerticalScroll.Value = 200;
        panel.ResumeLayout(true); // addition, calls PerformLayout
    }
}

字符串

相关问题