setting position of a control doesn't seem to work when scroll is 'moved' (c#, winforms)

夙愿已清 提交于 2020-01-14 10:18:13

问题


Description of the problem:

  • Create a 'custom control'. Set it's property AutoScroll to 'true'. Change it's bg-color to green.
  • Create second 'custom control'. Change it's bg-color to red.
  • On main form place first custom control
  • In code create 20 instances of second control
  • Add a button and in the button:
    • In code set their position in loop like c.Location = new Point(0, y);
    • y += c.Height;
  • Run App.
  • Press the button
  • Scroll the container
  • Press the button again and can someone please explain me WHY the 0 is not the beggining of the container form?! The controls are shifted...

Before you answer:

1) Yes the things need to be this way

2) Code sample below:

public partial class Form1 : Form
{
   List<UserControl2> list;

   public Form1()
   {
      InitializeComponent();
      list = new List<UserControl2>();
      for (int i = 0; i < 20; i++)
      {
         UserControl2 c = new UserControl2();
         list.Add(c);
      }
   }

   private void Form1_Load(object sender, EventArgs e)
   {
      foreach (UserControl2 c in list)
         userControl11.Controls.Add(c);
   }

   private void button1_Click(object sender, EventArgs e)
   {
      int y = 0;
      foreach (UserControl2 c in list)
      { 
         c.Location = new Point(0, y);
         y += c.Height;
      }
   }
}

回答1:


Its because Location gives the coordinates of the upper left corner of the control relative to the upper left corner of its container. So when you scroll down, the Location will change.

Here is how to fix it:

  private void button1_Click(object sender, EventArgs e)
  {
     int y = list[0].Location.Y;
     foreach (UserControl2 c in list)
     {
        c.Location = new Point(0, y);
        y += c.Height;
     }
  }



回答2:


The first item will not be at position 0 because at the time locations are calculated, the new item has not been added to the panel controls. Besides you should use AutoScrollPosition to ajust the positons. Here is my suggestion:

        int pos = (Container.AutoScrollPosition.Y != 0 ? Container.AutoScrollPosition.Y - newitem.Height : 0);

        if (Container.Controls.Count > 0)
        {
            foreach (Control c in Container.Controls)
            {
                c.Location = new Point(0, pos);
                pos += c.Height;
                }
            }                
        }
        newitem.Location = new Point(0, pos);
        Container.Controls.Add(newitem);


来源:https://stackoverflow.com/questions/2314611/setting-position-of-a-control-doesnt-seem-to-work-when-scroll-is-moved-c-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!