【问题标题】:ListViewItemCollection.Insert broken?ListViewItemCollection.Insert 坏了?
【发布时间】:2013-06-25 07:32:41
【问题描述】:

我试图允许用户将图像文件拖到 ListView 控件中,并在用户插入文件的任何位置显示图像。但是,由于某种原因,ListViewItemCollection.Insert 似乎没有在指定索引处插入项目,而是将其添加到列表的末尾。我正在使用从 ListView 继承的自定义控件,当文件被拖放到它上面时会引发一个事件:

//In my ListView control
var objPaths = (string[])(drgevent.Data.GetData(DataFormats.FileDrop));
if (objPaths != null && objPaths.Length > 0)
{
     var e = new DragDropFileEventArgs(objPaths, targetIndex);
     OnDropFile(e);
}

我在我的表单中使用它:

//Handle drag 'n dropped files
void imageListView_DropFile(object sender, DragDropFileEventArgs e)
{
    //Loads the files from e.Paths and returns the images added
    var addedImages = myListOfImages.LoadFromFiles(e.Paths, e.Index);

    for (int i = 0; i < addedImages.Length; i++)
    {
        var img = addedImages[i];
        ListViewItem.LargeImageList.Images.Add(img.Image);
        ListViewItem item = new ListViewItem((e.Index + i).ToString(), _imageList.Images.Count - 1);
        imageListView.Items.Insert(e.Index + i, item);
    }
}

但由于某种原因,这些项目被添加到 imageListView.Items 的末尾。

我可以使用以下代码在一个新项目中重现这一点:

        listView1.Items.Add("a");
        listView1.Items.Add("b");
        listView1.Items.Add("c");
        listView1.Items.Add("d");
        listView1.Items.Insert(1, "added");

添加的项目仍会到 ListView 的末尾。

有什么想法吗?我是否缺少 ListView 设置,或者这是一个错误?

编辑:我必须使用 View.LargeIcon,因为这样做的目的是在 ListView 中显示图像。我知道我可以从 ListView 中删除所有项目并一个一个地重新添加它们,但我正在寻找一种不会导致闪烁并且不会丢失我在 ListView 中的滚动位置的方法。

【问题讨论】:

    标签: c# .net listview controls


    【解决方案1】:

    只有在 View.List 模式下才能将项目插入 Listview 中的特定位置。下面的代码工作正常。请尝试它是否适合您。如果有用也请标记答案。

    ListView1.View = System.Windows.Forms.View.List
    ListView1.Items.Add("a")
    ListView1.Items.Add("b")
    ListView1.Items.Add("c")
    ListView1.Items.Add("d")
    ListView1.Items.Insert(1, "added")
    

    【讨论】:

    • 啊,这确实解决了问题,但我需要在 ListView 中显示图像,所以我必须使用 View = View.LargeIcon。还有其他方法吗?将其设置为 View.List,然后插入项目,然后将其设置回 View.LargeIcon 工作,但我失去了滚动位置,这是我试图避免的整个问题(即清除列表并重新填充它划痕)。
    猜你喜欢
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2017-12-14
    相关资源
    最近更新 更多