C# 实现OnCollectionChanged,以便ListBox自动更新WPF
我有这个对象包装器,我用它的实例填充集合:C# 实现OnCollectionChanged,以便ListBox自动更新WPF,c#,wpf,listbox,observablecollection,inotifycollectionchanged,C#,Wpf,Listbox,Observablecollection,Inotifycollectionchanged,我有这个对象包装器,我用它的实例填充集合: public class Multimedia : INotifyPropertyChanged { //... constructor //... getters and setters for the properties public void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { Observable
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;
}
}
XAML:
您不需要在多媒体中更改OnCollectionChanged
,而且ObservableCollection
已经实现了INotifyCollectionChanged
。看来问题出在别的地方了。你能为ListBox
显示你的XAML和绑定吗?@dkozl-我更新了我的问题帖子。当你添加时,你使用的是相同的mediaList
?是否异步添加?不,我没有异步方法。我没有完全理解你的评论。你是说当我添加addMedia()
方法时?您的意思是,我将新条目添加到mediaList
集合的另一个实例中吗?我的意思是,构造函数是您执行mediaList=new MultiMediaList()操作的唯一位置代码>之后,您只需执行mediaList.addMedia(…)
。您能展示一下如何添加项目吗?
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));
}
}
public partial class MainWindow : Window
{
MultiMediaList mediaList;
public MainWindow()
{
InitializeComponent();
mediaList = new MultiMediaList();
LB_media.ItemsSource = mediaList;
}
//...
}
<ListBox Name="LB_media" DisplayMemberPath="Title" ... />