【问题标题】:Moving all selected items in a ListBox with DataSource使用 DataSource 移动 ListBox 中的所有选定项目
【发布时间】:2018-11-20 07:12:50
【问题描述】:

我有一个ListBox,它有一个ObservableCollection<string> 作为它的DataSource。现在我希望能够向上或向下移动每个选定的项目。因此,如果列表看起来像这样(所选项目以 * 为前缀):

  Item 1
* Item 2
  Item 3
* Item 4
* Item 5
* Item 6
  Item 7

我希望它在向下移动一次后看起来像这样:

  Item 1
  Item 3
* Item 2
  Item 7
* Item 4
* Item 5
* Item 6

或者上移一次后的这个:

* Item 2
  Item 1
* Item 4
* Item 5
* Item 6
  Item 3
  Item 7

我已经偶然发现了ObservableCollection<T>.Move(int oldIndex, int newIndex),但我只能让它与移动单个项目一起工作。

什么是好的算法?

【问题讨论】:

  • 您是否尝试过使用 for 循环?向上移动时,让i0 运行到Count,向下移动时,让它向后运行

标签: c# .net winforms


【解决方案1】:

正如我在评论中已经提到的。您可以使用向前和向后循环来完成此操作。这是一个完成这项工作的示例程序。我做了按钮来区分向上和向下运动:

ObservableCollection<string> source = new ObservableCollection<string>();
private void Form1_Load(object sender, EventArgs e)
{
    for (int i = 1; i < 10; i++)
    {
        source.Add("Item " + i);
    }

    listBox1.DataSource = source;
}

private void buttonMoveUp_Click(object sender, EventArgs e)
{
    foreach (int index in listBox1.SelectedIndices)
    {
        if (index > 0) // don't move the first element upwards
        {
            source.Move(index, index - 1);
        }
    }

    listBox1.DataSource = null;
    listBox1.DataSource = source;
}

private void buttonMoveDown_Click(object sender, EventArgs e)
{
    for (int i = listBox1.SelectedIndices.Count - 1; i >= 0; i--)
    {
        int index = listBox1.SelectedIndices[i];
        if (index < source.Count-1) // don't move the last element downwards
        {
            source.Move(index, index + 1);
        }
    }            

    listBox1.DataSource = null;
    listBox1.DataSource = source;
}

【讨论】:

    【解决方案2】:

    如果所有选定的行都放下并且它们之间没有间隙,这将更容易(并且在某些情况下对用户来说更直观),但应该可以实现任何一种方式。您绝对可以使用 ObservableCollection 的 Move() 方法,要移动多个,您必须将多个 startindexes(对于每个选定项目)收集到一个列表中,然后使用 Move() 方法遍历该列表并进行一些基于计算根据光标所在的索引位置以及所选项目列表的排序顺序来确定每个项目的“新索引”是什么。

    编辑:还要记住更改索引的多米诺骨牌效应,您必须在计算中适应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多