2014-01-21 78 views
0

我試圖從列表視圖和目錄中刪除選定的項目文件,但我無法成功。我怎樣才能刪除這個。?從ImageFileCollectionViewModel中刪除ListView中的選定項目

string destination_dir = System.IO.Directory.GetCurrentDirectory() + @"./4x6"; 
    public ImggLList() 
    { 
    InitializeComponent(); 
    ListViewImage.Items.Clear(); 
    DataContextChanged += OnDataContextChanged; 


    ImageFileCollectionViewModel ImagesViewModel = new ImageFileCollectionViewModel(); 
    ImageFileControler.CompleteViewList(ImagesViewModel, destination_dir); 
    ListViewImage.DataContext = ImagesViewModel; 
    } 

OnDataContextChanged

private ImageFileCollectionViewModel _currentDataContext = null; 
     private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) 
     { 
      if (_currentDataContext == DataContext) return; 

      if (_currentDataContext != null) 
       _currentDataContext.SelectedImageFileViewModels = null; 

      _currentDataContext = DataContext as ImageFileCollectionViewModel; 
      if (_currentDataContext != null) 
       _currentDataContext.SelectedImageFileViewModels = ListViewImage.SelectedItems; 

     } 

按鈕功能:

private List<ImageFileViewModel> copyOfSelection; 

     private ImageFileCollectionViewModel imageFileCollection; 
     private void Delte_Photo_Click(object sender, RoutedEventArgs e) 
     { 
      copyOfSelection = imageFileCollection.SelectedImageFileViewModels.Cast<ImageFileViewModel>().ToList(); 

      foreach (ImageFileViewModel ifvm in copyOfSelection) 
      { 
       copyOfSelection.Remove(ifvm); 
       File.Delete(destination_dir); 
      } 

     } 

NullExeception錯誤: enter image description here

+0

我不相信你可以在foreach LO修改列表操作:http://stackoverflow.com/questions/6294983/modifying-list-inside-foreach-loop和這裏http://stackoverflow.com/questions/308466/how-to-modify-or-delete-items-from -enumerable-collection-while-iterating-thro – akousmata

+0

@akousmata:我該如何解決這個問題?請指導我。 – linguini

+0

使用我提供的兩個鏈接建議的循環標準。 – akousmata

回答

1
for (int i = 0; i < copyOfSelection.Count; i++) 
{ 
    copyOfSelection.RemoveAt(i); 
    File.Delete(destination_dir);   
} 
+0

我已初始化ImageFileCollectionViewModel&ImageFileViewModel,我得到空錯誤 – linguini

+0

在您的'OnDataContextChanged'方法中,您將'SelectedImageFileViewModels'設置爲null。我不確定你的代碼是如何工作的,但是當你試圖引用它時,這個對象是空的。這與如何從for循環中的列表中刪除項目無關。 – akousmata

+0

解決此問題的最佳方法是什麼?謝謝 – linguini