我想删除observablecollection
ObservableCollection<GetterSetter> _getterSetter = new ObservableCollection<GetterSetter>();
public ObservableCollection<GetterSetter> showList
{
get { return this._getterSetter; }
}
所以我的xaml文件是这样的,
<ListView x:Name="listView" Grid.Row="1" SelectionChanged="listView_SelectionChanged" Foreground="Black" ItemsSource="{Binding ListViewCollection}" SelectedItem="{Binding SelectedListViewItem,Mode=TwoWay}" SelectionMode="Single">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="180" DisplayMemberBinding="{Binding ShowName}"/>
</GridView>
我在这里有一个ShowName getter setter,
private string _showName;
public String ShowName{
get { return _showName; }
set
{
if (value == _showName) return;
_showName = value;
OnPropertyChanged();
}
我想要删除这样的选定项目,它会给我一个错误,
listView.Items.Remove(listView.SelectedItems[0]);
showList.RemoveAt(listView.Items.IndexOf(listView.SelectedItems[0]));
我也试过这个
var delete = SelectedListViewItem;
listView.Items.Remove(delete);
并且都给了我这个错误,
未处理的类型&#39; System.InvalidOperationException&#39;发生在PresentationFramework.dll
中其他信息:在使用ItemsSource时,操作无效。使用ItemsControl.ItemsSource访问和修改元素。
方式GetterSetter
是我的cs文件,我的第三个代码片段在哪里,
public GetterSetter SelectedListViewItem
{
get { return _selectedListViewItem; }
set
{
if (Equals(value, _selectedListViewItem)) return;
_selectedListViewItem = value;
OnPropertyChanged();
}
}
答案 0 :(得分:1)
正如错误所述,直接从ItemsSource执行此操作。要做到这一点,你需要将ItemsSource设置为它的类型,然后执行删除。
if(SelectedListViewItem != null)
{
// EDIT: Typo in the lambda for FirstOrDefault
var delete = showList.FirstOrDefault(x => SelectedListViewItem.ShowName == x.ShowName);
if(delete != null)
{
((ObservableCollection<GetterSetter>)listView.ItemsSource).Remove(delete);
}
}
编辑:NULL怪物正在抓住你。