Reputation: 2456
In Windows Phone I populate my Pivot control with an ObservableCollection model that gets its data from an SQL database with LINQ. This works very well on the initial setup.
But when I've done some changes to the DB and then I want to run the LINQ query again to reflect the changes to the UI (and the ObservableColletion), I've noticed that the ObservableCollection does not get the new values as I would expect from the LINQ query.
private ObservableCollection<ComicItem> m_showingComicsListModel;
public ObservableCollection<ComicItem> ShowingComicsListModel
{
...
}
...
var comicsSelectedInDB = from ComicItem item in comicListDb.Items
where item.IsShowing == true
select item;
m_showingComicsListModel = new ObservableCollection<ComicItem>(comicsSelectedInDB );
So when the showingComicsListModel
is evaluated the first time, it populates the model properly. But after I've done some changes to the DB and run this code a second time, the ShowingComicsListModel
has not changed and the setter is not called.
Any hints on what is the proper way to update an ObservableCollection with LINQ?
Upvotes: 2
Views: 1175
Reputation: 35544
You have two ways to resolve your problem.
First option is to Clear the existing ObservableCollection and add the result of the linq query to the Collection
var comicsSelectedInDB = from ComicItem item in comicListDb.Items
where item.IsShowing == true
select item;
m_showingComicsListModel.Clear();
foreach(var comic in comicsSelectedInDB) {
m_showingComicsListModel.Add(comic);
}
or
Second option is to raise the PropertyChangedEvent for the property ShowingComicsListModel to notify the UI that the bound property has changed. This solution requires that the class implements the INotifyPropertyChanged interface.
private ObservableCollection<ComicItem> m_showingComicsListModel;
public ObservableCollection<ComicItem> ShowingComicsListModel
{
get{ return m_showingComicsListModel;}
set{
m_showingComicsListModel = value;
RaisePropertyChanged("ShowingComicsListModel");
}
}
Upvotes: 1