滚动“移动”时,控件的设置位置似乎不起作用(c#,winforms)
问题描述:
- 创建“自定义控件”。 将其属性AutoScroll设置为“true”。 将它的bg颜色更改为绿色。
- 创建第二个“自定义控件”。 将它的bg颜色更改为红色。
- 在主窗体上首先进行自定义控件
- 在代码中创建第二个控件的20个实例
- 在按钮中添加一个按钮:
- 在代码中设置它们在循环中的位置,如c.Location = new Point(0,y);
- y + = c.Height;
- 运行App。
- 按下按钮
- 滚动容器
- 再次按下按钮,有人可以解释一下为什么0不是容器forms的开始?! 控件被转移……
在你回答之前:
1)是的,事情需要这样
2)下面的代码示例:
public partial class Form1 : Form { List list; public Form1() { InitializeComponent(); list = new List(); 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; } } }
因为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; } }
第一个项目不在位置0,因为在计算位置时,新项目尚未添加到面板控件。 此外,你应该使用AutoScrollPosition来调整位置。 这是我的建议:
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);