Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observablecollection not updating list, when an item gets added

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

Namespace: xmlns:local="clr-namespace:MusicPlayer.ViewModel"

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.

like image 611
HaloMediaz Avatar asked Mar 13 '16 20:03

HaloMediaz


2 Answers

Change your code to this:

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>();
    }
}

Just to explain why: every property of your ViewModel should notify of its changes.

like image 87
Arnaud Weil Avatar answered Sep 29 '22 22:09

Arnaud Weil


You should write this as itemsource

ItemsSource="{Binding ViewModel.TrackListObservable}"

And also set data context of windows to it self.

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" ...

With this property in MainWindow.

public AllTracksViewModel ViewModel { get; } = new AllTracksViewModel();

Note that you have to add items to this property. ViewModel.TrackListObservable

You should also remove

<UserControl.DataContext>
    <local:AllTracksViewModel/>
</UserControl.DataContext>

since the data context is the main window it self, thats why itemsource is set to ViewModel.TrackListObservable

like image 35
M.kazem Akhgary Avatar answered Sep 29 '22 21:09

M.kazem Akhgary