Implement OnCollectionChanged so that ListBox updates automatically WPF

白昼怎懂夜的黑 提交于 2020-01-25 17:33:50

问题


I have this object wrapper, whose instances I populate the collection with:

public class Multimedia : INotifyPropertyChanged
{
   //... constructor
   //... getters and setters for the properties

   public void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
   {
      ObservableCollection<Multimedia> objSender = sender as ObservableCollection<Multimedia>;
      NotifyCollectionChangedAction action = e.Action;
   }
}

The collection:

public class MultiMediaList : ObservableCollection<Multimedia>
{
    //... constructor with creating several default objects of Multimedia

    public void addMedia(string title, string artist, string genre, MediaType type)
    {
        this.Add(new Multimedia(title, artist, genre, type));
    }
}

So, I have a ListBox that is bound to the collection. When I start up the app, the default values are shown. But when I add a new entry to the collection - the ListBox does not get updated with the new item.

I guess I have not implemented correctly the OnCollectionChanged method, but I cannot grasp an idea of how to do it, from the examples that I have seen online, because every case is so different.

EDIT: Code-behind binding of the Collection and the ListBox:

public partial class MainWindow : Window
{
    MultiMediaList mediaList;
    public MainWindow()
    {
        InitializeComponent();
        mediaList = new MultiMediaList();
        LB_media.ItemsSource = mediaList;
    }

    //...
}

XAML:

<ListBox Name="LB_media" DisplayMemberPath="Title" ... />

来源:https://stackoverflow.com/questions/26929410/implement-oncollectionchanged-so-that-listbox-updates-automatically-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!