【发布时间】:2010-06-22 02:26:15
【问题描述】:
我在我的代码中有一个地方可以动态地将控件添加到自上而下排列的 FlowLayoutPanel。我需要控件以特定顺序出现,所以我每次都在清除 FlowLayoutPanel.Controls 集合,然后按照我希望它们出现的顺序添加每个子控件。我的代码是这样做的:
private void arrangement1()
{
flowLayoutPanel1.Controls.Clear();
flowLayoutPanel1.Controls.Add(control1);
flowLayoutPanel1.Controls.Add(control2);
flowLayoutPanel1.Controls.Add(control3);
}
大多数情况下,这很有效。但是,当在其后添加其他控件时,有一个特定控件不会保持其在控件集合中的位置。例如在以下代码段中:
private void arrangement2()
{
flowLayoutPanel1.Controls.Clear();
flowLayoutPanel1.Controls.Add(control1);
flowLayoutPanel1.Controls.Add(movingControl);
//movingControl current is at index = 1 in Controls.
flowLayoutPanel1.Controls.Add(control2);
//control2 is now at index = 1, movingControl got bumped to index = 2 in Controls.
flowLayoutPanel1.Controls.Add(control3);
//control3 is now at index =2, movingControl got bumped to index = 3 in Controls.
}
这只会在第一次将movingControl 添加到Controls 时发生。如果我回去打电话给安排1,然后再打电话给安排2。控件将按预期顺序显示:
- 控制1
- 移动控制
- 控制2
- 控制3
这似乎是 Controls.Add 代码中的一个错误。 .Add 行为的文档或文档都不完整,因为它并不总是添加到集合的末尾。有没有人知道为什么会发生这种情况。明显的“修复”是调用:
arrangement2();
arrangement1();
arrangement2();
但是,对于其他一些潜在问题,这似乎是一个非常糟糕的解决方案。
提前感谢您的帮助!
编辑:请注意,这些控件中的每一个都是自定义视图类的成员,因此它们在 Controls 集合被清除后仍然存在。但是,这些控件不存储在任何类型的有序集合中。他们只是这个自定义类的成员。上面显示的代码可以正常工作,如图所示。但是,在我的 GUI 程序的上下文中,它具有所描述的错误行为。如果我知道什么会有所帮助,我会发布更多代码,但是有很多代码涉及这些问题。这是为描述的操作执行的所有代码。
我真正要寻找的是什么可能的情况导致 Controls.Add 插入控件而不是集合的最后一个索引。特别是在调用 Clear() 并且没有调用 Remove() 之后。
【问题讨论】:
-
有一个类似的问题——我没有使用 Controls.Add(button),而是使用 Button.parent = flowLayoutPanel。这样做会导致顺序发生变化 - 切换到 controls.add 将所有内容按正确的顺序排列。
标签: c# .net user-interface flowlayoutpanel