C#UserControl.VerticalScroll.Value未设置

时间:2009-04-16 18:19:49

标签: c# winforms controls

我有一大堆C#代码应该在继承自UserControl的类中设置VerticalScroll.Value。当类的任何子对象改变大小时,它会被调用。该类的AutoScroll属性设置为true。

    public void ScrollTo(int top)
    {
        if (top >= this.VerticalScroll.Minimum && top <= this.VerticalScroll.Maximum)
        {
            this.VerticalScroll.Value = top;
        }
    }

问题是,在遍历代码时,有时会设置this.VerticalScroll.Value,有时它会保留调用此方法之前的值。

这是VS中的错误,还是存在值忽略尝试设置它的已知条件?

谢谢, 罗布

4 个答案:

答案 0 :(得分:20)

我遇到了同样的问题,并在一些开发论坛中找到了解决方案。设置VerticalScroll.Value后,您必须调用PerformLayout()以使滚动控件更新。所以这样做:

scrollingcontrol.VerticalScroll.Value = top;
scrollingcontrol.PerformLayout();

这比设置.Value两次更有意义,虽然看起来效果相同。

答案 1 :(得分:3)

我遇到了同样的问题,我在MSDN网页上找到了一个解决方案(不会让我发布链接,因为我是新用户)。

建议的解决方案是分配给.Value两次,它对我有用:

int newVerticalScrollValue = 
         pDashboard.VerticalScroll.Value - pDashboard.VerticalScroll.SmallChange;

pDashboard.VerticalScroll.Value = newVerticalScrollValue;
pDashboard.VerticalScroll.Value = newVerticalScrollValue;

答案 2 :(得分:0)

FlowLayoutPanel似乎是一个不同的野兽。滚动条确实向下移动,但是flowlayoutpanel.VerticalScroll.Value的值保持为0.我尝试了上述所有技术以及一些DoEvents()和Thread.Sleep(),甚至是在进行下一次迭代之前完全屈服的计时器。一切都失败了。我最终发现DisplayRectangle.Y立刻表达了滚动更改......

private void PrintButton_Click(object sender, EventArgs e)
{
    FlowLayoutPanel flp = TheBuildFlowLayoutPanel;
    List<Bitmap> printPics = new List<Bitmap>();
    int printLastY = 100;
    flp.VerticalScroll.Value = 0;
    while (flp.DisplayRectangle.Y < printLastY) // DisplayRect.Y becomes successively more negative
    {
        Bitmap bmp = new Bitmap(flp.Width, flp.Bounds.Height);
        printPics.Add(bmp);
        flp.DrawToBitmap(bmp, flp.ClientRectangle);
        printLastY = flp.DisplayRectangle.Y;
        flp.VerticalScroll.Value = Math.Min(flp.VerticalScroll.Maximum, flp.VerticalScroll.Value + flp.Height);
    }

    flp.VerticalScroll.Value = 0;
    for (int i = 0; i < printPics.Count; i++)
    {
        printPics[i].Save("C:\\Temp" + i.ToString() + ".bmp");
    }
}

答案 3 :(得分:0)

在我的情况下,有必要将VerticalScroll.Value设置为不同的值,然后设置为感兴趣的值,例如

this.panel1.VerticalScroll.Value = verticalScrollPosition - 1;
this.panel1.VerticalScroll.Value = verticalScrollPosition;   

请注意滚动位置始终在VerticalScroll.Minimum和VerticalScroll.Maximum之间。