2011-06-21 14 views
2

我有一個列表框,每行包含一個「圖像」和一個「TextBlock」。當我在後面刪除一個一行類似的代碼:在只讀集合上不支持的操作

this.UserListBox.Items.RemoveAt(this.UserListBox.SelectedIndex); 

有它拋出一個異常:不支持只讀集合

操作。

如何從列表框中刪除行?

我正在寫一個Windows Phone 7 APP。

+0

有你的數據綁定的ur列表框到任何集合? –

回答

4

如果您在ListBox上設置ItemsSource,則Items將在內部生成並且是隻讀的。在這種情況下,您需要從supoplied項目集合中刪除項目。如果集合實現INotifyCollectionChanged,則集合更改將反映在列表框中。

+0

要添加到此答案,'ObservableCollection'是一個實現了'INotifyCollectionChanged'的列表。 –

+0

謝謝,它工作。我用ObservableCollection替換List。 – Joel

+0

@JanSlodicka我看到,當爲ListBox設置ItemsSource時,Items不會立即生成,如何在設置ItemsSource後強制生成Item? – onmyway133

0

而不是將列表項綁定到您的列表框的itemsSource,而應該使用ObservableCollection。這將解決問題。 ObservabeCollection有一個刪除方法,你可以使用

UserListBox.Items.Remove(this.UserListBox.SelectedItem);