【问题标题】:Listview Delete Item Index source is in use wpfListview删除项目索引源正在使用wpf
【发布时间】:2015-12-10 19:06:24
【问题描述】:

我想从我的 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);

两者都给了我这个错误,

PresentationFramework.dll 中出现“System.InvalidOperationException”类型的未处理异常

附加信息:使用 ItemsSource 时操作无效。改为使用 ItemsControl.ItemsSource 访问和修改元素。

顺便说一句GetterSetter是我的cs文件,我的第三个代码sn-p在哪里,

public GetterSetter SelectedListViewItem
    {
        get { return _selectedListViewItem; }
        set
        {
            if (Equals(value, _selectedListViewItem)) return;
            _selectedListViewItem = value;
            OnPropertyChanged();
        }
    }

【问题讨论】:

    标签: c# wpf listview items


    【解决方案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 怪物正在抓你。

    【讨论】:

    • 现在它给了我“在 mscorlib.dll 中发生了“System.ArgumentOutOfRangeException”类型的未处理异常附加信息:索引超出范围。必须是非负数并且小于集合的大小。”在这行代码,showNameBox.Text = showList[listView.Items.IndexOf(listView.SelectedItems[0])].ShowName;
    • SelectedListViewItem 到底是什么?它是在哪里定义的?
    • 它是在xaml代码中定义的,你可以在第二个代码sn-p中看到它
    • 它绑定到一个属性,但我需要知道那个属性是什么类型。
    • 好的,我看到我编辑了我的问题,你可以在最后一个代码 sn-p 上看到它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2012-06-22
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    相关资源
    最近更新 更多