从绑定集合中删除项目时的奇怪行为

时间:2016-03-05 18:40:50

标签: c# windows xaml win-universal-app

我有一个与OservableCollection数据绑定的ListView ..我需要创建一个按钮,根据UI的ListView的选定项目从集合中删除项目。

我的XAML:

<ListView Name="MyListView"
          ItemsSource="{Binding}"
          SelectionMode="Multiple"/>

<Button Name="RemoveButton"
        Click="RemoveButton_Click" />

我的C#:

 private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        MyListView.DataContext = this.ItemsCollection; 
      // ItemsCollection is the ObservableCollection
    }

  private void RemoveButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in MyListView.SelectedItems)
        {
            ItemsCollection.Remove((Item)item);
        }
    }

现在发生的事情就是每当我点击RemoveButton时,第一个选中的项目被移除但是后面的那个项目没有被删除等等,例如,如果我的ListView显示了这个:

第1项 第2项 第3项 第4项 第5项 第6项

然后选择所有项目并点击删除使ListView显示:

第2项 第4项 第6项

并重复选择和删除显示:

第4项

所以你可以看到它删除了一个项目而离开了下一个..为什么这个奇怪的行为?我错过了什么?

1 个答案:

答案 0 :(得分:1)

这将有效..

private void RemoveButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in MyListView.SelectedItems.Cast<object>().ToList())
        {
            ItemsCollection.Remove((Item)item);
        }
    }

您可以在此处查看完整代码:

public partial class MainWindow : Window
{
    public ObservableCollection<Person> _personList { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        _personList = new ObservableCollection<Person>();
        _personList.Add(new Person() { Name = "Person1" });
        _personList.Add(new Person() { Name = "Person2" });
        _personList.Add(new Person() { Name = "Person3" });
        _personList.Add(new Person() { Name = "Person4" });
        _personList.Add(new Person() { Name = "Person5" });
        _personList.Add(new Person() { Name = "Person6" });

        MyListView.DataContext = this._personList;
    }

    private void RemoveButton_Click(object sender, RoutedEventArgs e)
    {
        foreach (var item in MyListView.SelectedItems.Cast<object>().ToList())
        {
            _personList.Remove((Person)item);
        }
    }
}

public class Person
{
    public string Name { get; set; }
}

<Window x:Class="ListView.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ListView"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
    <ListView Background="DarkCyan" Foreground="White" Name="MyListView"
      ItemsSource="{Binding}" Height="200" DisplayMemberPath="Name"
      SelectionMode="Multiple"/>

    <Button Name="RemoveButton"
    Click="RemoveButton_Click" Height="100" Width="100" />
    </StackPanel>
</Grid>