如何在ListView中更改项目索引?

6

我有一个listView和两个按钮(UP,DOWN),我想将选定的项目向上或向下移动。

我考虑过在选定项和上面的一项之间交换...但是我尝试的代码不合理,因为索引是只读的。

同时,使用我的或某些人的方法都行不通...我根本不能操纵索引。

private void btnDown_Click(object sender, EventArgs e)
    {
         listView1.SelectedItems[0].Index--; // It's ReadOnly.
    }


那么,我如何让用户像VB一样更改ListViewItem索引,就像图片中所示的那样?

enter image description here

提前感谢...


笑- 代码?如果没有先看到您的代码中有用的东西,我该如何生成代码呢?- 您使用日期填充列表的来源- 我不知道如何,但您必须这样做- 并且这些数据是您应该更改要切换的项目顺序的地方 - Random Dev
1
@CarstenKönig 像 M4N 刚才那样。 - Murhaf Sousli
那么你从中得到了什么?当然,用户会看到更改的顺序,但这些数据是否会被持久化?我的意思是,您的用户可能有更改顺序的原因,对吧?M4N提供的是UI中的hack - 即意味着代码混乱 - 不是一个好的模式,但继续吧... - Random Dev
这是一个文件传输应用程序。我想让用户对添加的项目进行排序(从另一个列表视图中),因为顺序对于文件传输很重要,发送方法取决于该索引。@CarstenKönig - Murhaf Sousli
@CarstenKönig,请看一下这是我的应用程序... http://stackoverflow.com/questions/9663528/how-to-check-if-the-item-name-subitems-text-is-already-exists-in-another-li - Murhaf Sousli
显示剩余3条评论
3个回答

15
你需要先移除选中的项,然后在新的位置重新添加它。
例如,将该项上移一个位置:
var currentIndex = listView1.SelectedItems[0].Index;
var item = listView1.Items[index];
if (currentIndex > 0)
{
    listView1.Items.RemoveAt(currentIndex);
    listView1.Items.Insert(currentIndex-1, item);
}

0
以下是对M4N答案的改进,以处理将项目重新排序为列表顶部并将其放置在列表底部。
int currentIndex = listView1.SelectedItems[0].Index;
ListViewItem item = listView1.Items[currentIndex];
if (currentIndex > 0)
{
    listView1.Items.RemoveAt(currentIndex);
    listView1.Items.Insert(currentIndex - 1, item);
}
else
{
    /*If the item is the top item make it the last*/
    listView1.Items.RemoveAt(currentIndex);
    listView1.Items.Insert(listView1.Items.Count, item);
}

0
在可观察集合的情况下,您还可以调用:.Move(currentindex, newindex);

MSDN


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接