.net c#删除ObservableCollection项目

Removing ObservableCollection Item
2020-11-24
  •  译文(汉语)
  •  原文(英语)

我创建了一个ObservableCollection并将其绑定到我的Listview.在将我的项目加载到ListView之前,将使用Linq对它们进行排序,然后将其添加到ListView中:

//Get's the Items and sets it
public ObservableCollection<ItemProperties> ItemCollection { get; private set; }

//Orders the Items alphabetically using the Title property
DataContext = ItemCollection.OrderBy(x => x.Title);

<!--ItemCollection has been binded to the ListView-->
<ListView ItemsSource="{Binding}"/>

我遇到的问题是我无法从集合中删除选定的项目.仅当我添加时,才会出现问题DataContext = ItemCollection.OrderBy(x => x.Title);.如果是DataContext = ItemCollection这样,我可以删除所选项目.

打开ContextMenu(MenuFlyout)并单击"删除"项后,我的删除方法即被激活.我的删除方法是:

private void btn_Delete_Click(object sender, RoutedEventArgs e)
{
   var edit_FlyOut = sender as MenuFlyoutItem;
   var itemProperties = edit_FlyOut.DataContext as ItemProperties;
   ItemCollection.Remove(itemProperties);
}

这是我的ItemProperties类:

public class ItemProperties : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public ItemProperties() { }
    private string m_Title;
    public string Title
    {
        get { return m_Title; }
        set
        {
            m_Title = value;
            OnPropertyChanged("Title");
        }
    }
    private string m_Post;
    public string Post
    {
        get { return m_Post; }
        set
        {
            m_Post = value;
            OnPropertyChanged("Post");
        }
    }
    private string m_Modified;
    public string Modified
    {
        get { return m_Modified; }
        set
        {
            m_Modified = value;
            OnPropertyChanged("Modified");
        }
    }
    private string m_ID;
    public string ID
    {
        get { return m_ID; }
        set
        {
            m_ID = value;
            OnPropertyChanged("ID");
        }
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(name));
    }
}

编辑

我如何装载物品:

public async void GetList()
 {
    var AppStorage = ApplicationData.Current.LocalFolder;
    var noteFolders = await AppStorage.GetFolderAsync(@"folder\files\");
    var Folders = await noteFolders.GetFoldersAsync();

    ItemCollection = new ObservableCollection<ItemProperties>();
    foreach (var noteFolder in Folders)
      {

         ItemCollection.Add(new ItemProperties { Title = readTitle, Post = readBody, ID = noteFolder.Name, Modified = timeFormat });
      }
      //code which readers and adds text to the properties...
      DataContext = ItemCollection.OrderBy(x => x.Title);
}
速聊1:
btn_Delete_Click应该只删除集合中的选定项目.MenuFlyoutItem是一个contextMenu.当用户持有ListViewItem时,将MenuFlyoutItem显示该Delete选项,而当他单击它时,应该只删除selected ListViewItem.我已经添加了DataContext as ItemProperties以获得整个ListViewItem对象,因此它删除了Item.希望这是有道理的.
解决过程1

您可以从ListView中获取选定的项目并将其删除:

if (lvElement.SelectedIndex == -1) return;
ItemProperties selectedProperty = (ItemProperties)lvElement.SelectedItem;

// remove selectedProperty from original collection
速聊1:
谢谢,但我已经有了答案.我会尽快发布.
解决过程2

我的解决方案是:

ItemCollection = new ObservableCollection<ItemProperties>(ItemCollection.OrderBy(a => a.Title));
DataContext = ItemCollection;

似乎我不得不将ItemCollection重新初始化为一个新的ObservableCollection并一次性对其进行排序,而不是加载项目然后进行排序.这是因为它有一个列表,该列表首先添加项目,然后添加另一个必须排序的列表.为了避免这种情况,我一口气做到了.以上帮助了我.我从这里得到的.

速聊1:
您可能要考虑使用WPFCollectionViewSource对项目进行排序和分组,而不是在设置DataContext
速聊2:
是.我将把它用于其他用途,而不是其他用途.

I have created an ObservableCollection and binded that to my Listview. Before my items are loaded into the ListView they are being sorted using Linq and then added to the ListView:

//Get's the Items and sets it
public ObservableCollection<ItemProperties> ItemCollection { get; private set; }

//Orders the Items alphabetically using the Title property
DataContext = ItemCollection.OrderBy(x => x.Title);

<!--ItemCollection has been binded to the ListView-->
<ListView ItemsSource="{Binding}"/>

The problem I'm having is that I can't remove a selected item from the collection. The problem occurs only if I add the DataContext = ItemCollection.OrderBy(x => x.Title);. If it's DataContext = ItemCollection then I can delete the selected item.

My delete method gets activated once the ContextMenu (MenuFlyout) is being opened and the 'Delete' item is clicked. My delete method is:

private void btn_Delete_Click(object sender, RoutedEventArgs e)
{
   var edit_FlyOut = sender as MenuFlyoutItem;
   var itemProperties = edit_FlyOut.DataContext as ItemProperties;
   ItemCollection.Remove(itemProperties);
}

This is my ItemProperties class:

public class ItemProperties : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public ItemProperties() { }
    private string m_Title;
    public string Title
    {
        get { return m_Title; }
        set
        {
            m_Title = value;
            OnPropertyChanged("Title");
        }
    }
    private string m_Post;
    public string Post
    {
        get { return m_Post; }
        set
        {
            m_Post = value;
            OnPropertyChanged("Post");
        }
    }
    private string m_Modified;
    public string Modified
    {
        get { return m_Modified; }
        set
        {
            m_Modified = value;
            OnPropertyChanged("Modified");
        }
    }
    private string m_ID;
    public string ID
    {
        get { return m_ID; }
        set
        {
            m_ID = value;
            OnPropertyChanged("ID");
        }
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(name));
    }
}

Edit

How I load my Items:

public async void GetList()
 {
    var AppStorage = ApplicationData.Current.LocalFolder;
    var noteFolders = await AppStorage.GetFolderAsync(@"folder\files\");
    var Folders = await noteFolders.GetFoldersAsync();

    ItemCollection = new ObservableCollection<ItemProperties>();
    foreach (var noteFolder in Folders)
      {

         ItemCollection.Add(new ItemProperties { Title = readTitle, Post = readBody, ID = noteFolder.Name, Modified = timeFormat });
      }
      //code which readers and adds text to the properties...
      DataContext = ItemCollection.OrderBy(x => x.Title);
}
Talk1:
btn_Delete_Click is supposed to remove only the selected item in the collection. MenuFlyoutItem is a contextMenu. When the user holds the ListViewItem the MenuFlyoutItem shows the Delete option and when he clicks it, it's supposed to delete only the selected ListViewItem. I've added DataContext as ItemProperties to get the whole ListViewItem Object so it deletes the Item. Hopefully that makes sense.
Solutions1

You can get selected item from ListView and delete it:

if (lvElement.SelectedIndex == -1) return;
ItemProperties selectedProperty = (ItemProperties)lvElement.SelectedItem;

// remove selectedProperty from original collection
Talk1:
Thank you but I've already got an answer. I'll be posting it soon.
Solutions2

My solution is:

ItemCollection = new ObservableCollection<ItemProperties>(ItemCollection.OrderBy(a => a.Title));
DataContext = ItemCollection;

It seemed like I had to reinitialize the ItemCollection to a new ObservableCollection and order it all in one go rather than loading the items then sorting. What this did was it had one list which was first adding the items then the other list which had to sort. To avoid this I had do to it all in one go. Above helped me. I got it from here.

Talk1:
You might want to consider using WPF's CollectionViewSource for sorting and grouping items rather than performing the sort prior to setting the DataContext
Talk2:
Yes. I'm going to be using it for something else rather than this.
转载于:https://stackoverflow.com/questions/28121832/removing-observablecollection-item

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入