简体   繁体   中英

Strange AutoScroll behavior

Introduction

I have written a simple user control.

The control contains a FlowLayoutPanel and a button on it.

The button click event handler is as follows:

private void uxAdd_Click(object sender, EventArgs e)
{
    count++;
    Label label = new Label();
    label.Text = "Label " + count.ToString();
    uxFlowLayout.Controls.Add(label);
}

The Add button adds a label onto the FlowLayoutPanel and because the FlowLayoutPanel.AutoSize and control's AutoSize properties are equal to true and FlowLayoutPanel.FlowDirection is equal to TopDown the control will be increased in height.

I've put my user control on a form and set the form's AutoScroll property to true.

Also I wrote the following Layout event handler:

private void MainForm_Layout(object sender, LayoutEventArgs e)
{
    uxSection.Width = this.ClientSize.Width;
}

( uxSection is a user control that I'm talking about in the beginning of the Introduction section)

Problem

Here is what I'm doing:

Step 0 . Run the program.

Step 1 . Add a few labels so that the vertical scrollbar will appear.

Step 2 . Scroll to the bottom of the form.

Step 3 . Resize the form horizontally.

在此处输入图片说明

As you can see, after resizing the form, the scrollbar position is not at the bottom (I expect it to be at the bottom).

So the question is, what am I missing? Why does the scrollbar resets to the top?

This happens because the whole control is redrawn upon a resize.

You'll want to either keep the location of the scrollbar saved in a variable so that when the resize event occurs you can reset the position of the scrollbar OR you'll want to push the scroll bar to the bottom of the list when a resize event is fired by using the number of items in your list to calculate where the bottom element is and then pushing the scrollbar to that position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM