2017-04-05 58 views
0

我有一個Book和List類。我使用ListView來顯示我的列表,並且我想在按鈕按下時移除選定的項目。 這是我的方法:C#WPF:刪除列表中收到的ListView.Selecteditems中的項目

private void currentlyReadingRemoveItem_Click(object sender, RoutedEventArgs e) 
    { 
     var selectedItems = CurrentlyReadingBooksListView.SelectedItems; 
     _currentlyReadingBooks.Except((List<Book>)selectedItems); 
    } 

不過,我得到這個錯誤:

System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.SelectedItemCollection' to type 'System.Collections.Generic.List`1[BookshelfLibrary.Book]'.'

我一直在試圖解決這一過去的小時,我嘗試了一些其他的鑄造方法,我甚至不知道還有什麼,我太累了想不到。 這是整個項目:https://github.com/GoldenDragonPC/Bookshelf

在此先感謝您。編輯: 工作代碼。

  var selectedItems = CurrentlyReadingBooksListView.SelectedItems; 
     var test = _currentlyReadingBooks.Except(selectedItems.Cast<Book>()); 
     _currentlyReadingBooks = test.ToList(); 
     WriteData(_currentlyReadingBooks, CurrentlyReadingPath); 
     InitializeList(); 

回答

0

嘗試使用linq的cast方法。喜歡的東西:

_currentlyReadingBooks.Except(selectedItems.Cast<Book>()?.ToList()); 

更新

_currentlyReadingBooks = _currentlyReadingBooks.Except(selectedItems.Cast<Book>()).ToList(); 
+0

此外,還要確保你做的返回值的東西。 'Except'不能就地運行,它會返回一個IEnumerable。 – MrZander

+0

謝謝,但雖然這不會引發任何錯誤,但由於某種原因,它實際上並未從列表中刪除項目。我剛看到我需要用返回變量做一些事情,幾分鐘後就會嘗試。 –

+0

謝謝你們,明白了。 –