在常规面板中重新排序控件

Reordering controls in a regular panel

ContolPanel 的类型是:FlowLayoutPanel 发件人是我点击的面板。

如何重新排序我的用户控件在我的 FlowLayoutPanel 中设置的顺序?

这就是我将 Objekts(UserControls) 添加到 FlowLayoutPanel 的方式

private void button1_Click_1(object sender, EventArgs e)
    {
        int count = 0;
        var panel = sender as Panel;
        switch (panel.Name)
        {

            case "TypePanel":
                ContolPanel.Controls.Add(new Type().Initialize(_ConnectionStr, _connection, _brugerLNr, _klinikLNr, _speciale, _ICPC, _segmenterStrings).SetModifiedCallBack(FilterModified));
                break;
        }
    }    

我添加了 4-5 次,一次有很多不同,这只是一次。 使用“+”和“-”按钮重新排序的最佳方法是什么?

我不想将所有控件保存在 List<Controls> 中,然后用

之类的东西重新排序它们
ControlList[1] = ControlList[2]

然后将列表中的所有控件插入到 FlowLayoutPanel 中。 但这似乎对我不起作用。有没有一种简单的方法可以做到这一点?

您可以将用户控件添加到面板并将用户控件的 Dock 属性 设置为 DockStyle.Top,然后最好将 z-order of user control using Parent.SetChildIndex 更改为移动它向上或向下。

为此,请将这两个方法添加到您的用户控件中:

public void MoveUp()
{
    if (this.Parent == null)
        return;

    var index = this.Parent.Controls.GetChildIndex(this);
    if (index <= this.Parent.Controls.Count)
        this.Parent.Controls.SetChildIndex(this, index + 1);
}

public void MoveDown()
{
    if (this.Parent == null)
        return;

    var index = this.Parent.Controls.GetChildIndex(this);
    if (index > 0)
        this.Parent.Controls.SetChildIndex(this, index - 1);
}

您还可以支持使用 + 向上移动和使用 - 键向下移动,方法是覆盖用户中的 ProcessCmdKey控制:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    switch (keyData)
    {
        case Keys.Add:
            this.MoveUp();
            break;
        case Keys.Subtract:
            this.MoveDown();
            break;
        default:
            break;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}

您还可以在用户控件中添加上移 Button 和下移 Button 并在用户控件中处理这些按钮的 Click 事件:

private void MoveUpButton_Click(object sender, EventArgs e)
{
    this.MoveUp();
}

private void MoveDownButton_Click(object sender, EventArgs e)
{
    this.MoveDown();
}

由于我们创建了 MoveUpMoveDown public,您可以在表单中上下移动用户控件:

myUserControl1.MoveUp();