添加项目时,ObservableCollection不更新列表 [英] Observablecollection not updating list, when an item gets added
本文介绍了添加项目时,ObservableCollection不更新列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用MVVM模式,并希望使用可观察的集合来更新ListView.我经历了几个SO问题,但看不到我在做什么错.任何帮助深表感谢.谢谢.
I'm using the MVVM pattern and want to update a ListView using an observable collection. I went through several SO questions, but cannot see what I'm doing wrong. Any help is much appreciated. Thanks.
View.xaml
命名空间:xmlns:local="clr-namespace:MusicPlayer.ViewModel"
DataContext
DataContext
<UserControl.DataContext>
<local:AllTracksViewModel/>
</UserControl.DataContext>
ListView
<ListView x:Name="TrackListView"
ItemsSource="{Binding Path=TrackListObservable}">
...
<ListView.View>
<GridView>
<GridViewColumn Header="Title" Width="250" DisplayMemberBinding="{Binding Title}" />
<GridViewColumn Header="Album" Width="200" DisplayMemberBinding="{Binding Album}" />
<GridViewColumn Header="Artist" Width="150" DisplayMemberBinding="{Binding Artist}" />
<GridViewColumn Header="Duration" Width="100" DisplayMemberBinding="{Binding FormattedDuration}" />
</GridView>
</ListView.View>
</ListView>
ViewModel.cs
public class AllTracksViewModel
{
public ObservableCollection<Track> TrackListObservable { get; private set; }
public AllTracksViewModel()
{
TrackListObservable = new ObservableCollection<Track>();
}
}
我验证了项目肯定会添加到可观察项目中. 再次感谢您的帮助.
I verified that items are definitely getting added to the observable. Again, thanks for the help.
推荐答案
将代码更改为此:
public class AllTracksViewModel : INotifyPropertyChanged
{
ObservableCollection<Track> trackListObservable;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Track> TrackListObservable {
get { return trackListObservable; }
set {
trackListObservable = value;
if(PropertyChanged!=null) {
PropertyChanged(this, new PropertyChangedEventArgs("TrackListObservable"));
}
}
}
public AllTracksViewModel()
{
TrackListObservable = new ObservableCollection<Track>();
}
}
仅说明原因:ViewModel的每个属性都应通知其更改.
Just to explain why: every property of your ViewModel should notify of its changes.
这篇关于添加项目时,ObservableCollection不更新列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文