滚动"移动"时,控件的设置位置似乎不起作用(c#,winforms)

arg*_*rgh 4 c# scroll position winforms

问题描述:

  • 创建"自定义控件".将其属性AutoScroll设置为"true".将它的bg颜色更改为绿色.
  • 创建第二个"自定义控件".将它的bg颜色更改为红色.
  • 在主窗体上第一个自定义控件
  • 在代码中创建20个第二个控件的实例
  • 在按钮中添加一个按钮:
    • 在代码中设置它们在循环中的位置,如c.Location = new Point(0,y);
    • y + = c.Height;
  • 运行App.
  • 按下按钮
  • 滚动容器
  • 再次按下按钮,有人可以解释一下为什么0不是容器形式的开始?!控件被转移......

在你回答之前:

1)是的,事情需要这样

2)以下代码示例:

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;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

SwD*_*n81 6

因为Location给出了控件左上角相对于其容器左上角的坐标.因此,当您向下滚动时,位置将会更改.

以下是如何修复它:

  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;
     }
  }
Run Code Online (Sandbox Code Playgroud)

  • 我真的很好奇,根据滚动位置更改位置值的想法是什么? (8认同)