删除多个项目并从ListView ObserverCollection中删除所有项目

时间:2014-02-17 15:10:01

标签: wpf listview c#-4.0 listviewitem

我可以通过这种方式从图像的ListView中删除所选项目:

private void Delte_Photo_Click(object sender, RoutedEventArgs e)
        {
            if (ListViewImage.SelectedItem == null)
            {
                MessageBox.Show("Please select an image to be removed...");
                return;
            }

            ImageFileCollectionViewModel viewModel = ListViewImage.DataContext as ImageFileCollectionViewModel;
            if (viewModel != null)
            {
                ImageFileViewModel image = ListViewImage.SelectedItem as ImageFileViewModel;//ListViewImage is the listBox
                if (image != null)
                {
                    //remove physical file from disk:
                    File.Delete(image.FileName);
                    //remove item from ObservableCollection:
                    viewModel.AllImages.Remove(image);
                }
            }
        }

如何删除多张图片? 如何删除所有图像?点击按钮。

1 个答案:

答案 0 :(得分:1)

通过foreach

迭代你的imagecollection
foreach(var image in viewModel.AllImages.ToList()){
    File.Delete(image.FileName);
    viewModel.AllImages.Remove(image);
}

一次删除多个实例:

        // let's say these are the positions of your items to remove
        var positions = new List<int>() { 1, 4, 6 };
        var list = viewModel.AllImages.ToList();

        // this removes all objects on the given index
        foreach (var position in positions)
        {
           list.RemoveAt(position);
        }

如果要通过objectreference删除迭代通过要删除的对象集合。