c# - ListView 移动项目

标签 c# winforms listview

ListView 有另一个问题:( 现在我需要在组中移动项目(向上、向下、到开头、到结尾),但是 ListView 总是在最后显示移动的项目。

这是将项目移到开头的示例代码:

   if (1 == listView1.SelectedItems.Count)
    {

        ListViewItem item = listView1.SelectedItems[0];
        ListViewGroup gp = item.Group;

        int index;
        index = item.Index;

        if (index < listView1.Items.Count)
        {

            index = 0;

            listView1.Items.Remove(item);

            item.Group = gp;

            listView1.Items.Insert(index, item);
        }
    }

我尝试谷歌寻找一些解决方案,我发现其他人 ( http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/838f90cd-33d8-4c81-9ed9-85220b511afe ) 和我有同样的问题,但他的解决方案不起作用:(

我考虑过使用 ObjectListView,但我修改了 ListView,女巫现在支持带有 WinAmp 效果的拖放、onScroll 事件、滚动同步等。我不想丢失这些东西:(

最佳答案

试试这个:

/// <summary>
/// Move the given item to the given index in the given group
/// </summary>
/// <remarks>The item and group must belong to the same ListView</remarks>
public void MoveToGroup(ListViewItem lvi, ListViewGroup group, int indexInGroup) {
    group.ListView.BeginUpdate();
    ListViewItem[] items = new ListViewItem[group.Items.Count + 1];
    group.Items.CopyTo(items, 0);
    Array.Copy(items, indexInGroup, items, indexInGroup + 1, group.Items.Count - indexInGroup);
    items[indexInGroup] = lvi;
    for (int i = 0; i < items.Length; i++)
        items[i].Group = null;
    for (int i = 0; i < items.Length; i++) 
        group.Items.Add(items[i]);
    group.ListView.EndUpdate();
}

关于c# - ListView 移动项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1189375/

相关文章:

c# - 如何在 C# 中编写 Windows 7 小工具?

c# - 如何在加载数据时显示启动画面以消磨时间?

c# - Windows窗体应用程序中的记录错误

c# - 获取数据以在 ListView DataTemplate 中显示

c# - 使用 AutoFaker 将 RuleFor 设置为 null

c# - 我如何计算矢量的反面,增加一些松弛

c# - 如何从我的 Web API 响应中删除 header ?

c# - 如何让主窗口等到新打开的窗口在 C# WPF 中关闭?

java - 刷新 ListView 数据库

c# - 将 CheckBox IsChecked 属性绑定(bind)到 ListView 的 SelectedItems 属性