如何反转FlowLayoutPanel?

时间:2016-03-10 20:34:37

标签: c# flowlayoutpanel controlcollection

我正在尝试颠倒FlowLayoutPanel中控件的顺序。

我尝试将ControlCollection转换为数组,然后将其反转并清除ControlCollection,然后读取控件。但这似乎没有计划效果。

这是我使用的代码:

private static void ReverseLayout(Control control, bool suspend = true) {
     if (suspend) control.SuspendLayout();
     Control[] newCC = new Control[control.Controls.Count];
     control.Controls.CopyTo(newCC, 0);
     Array.Reverse(newCC);
     control.Controls.Clear();
     //control.Controls.AddRange(newCC);
     for (int i = 0; i < newCC.Length; i++) {
        newCC[i].Location = new System.Drawing.Point(); // maybe? no :\
        newCC[i].TabIndex = i; // maybe? no :\
        control.Controls.Add(newCC[i]);
     }
     if (suspend) control.ResumeLayout(false);
  }

1 个答案:

答案 0 :(得分:0)

您的代码似乎比它需要的更复杂。尝试将控件放在List<Control>中,然后在其上调用reverse,将集合放回:

int firstTabIndex = flp.Controls[0].TabIndex;
List<Control> controls = flp.Controls.Cast<Control>().ToList();
flp.Controls.Clear();
controls.Reverse();
flp.Controls.AddRange(controls.ToArray());

对于TabIndex属性,您必须重新应用值:

for (int i = 0; i < flp.Controls.Count; ++i) {
  flp.Controls[i].TabIndex = firstTabIndex + i;
}