Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows 8 CollectionViewSource ObservableCollection Binding Not Updating

I have a CollectionViewSource that is binding to an subset of an observable collection to show the top n articles on the main page.

<CollectionViewSource
        x:Name="groupedItemsViewSource"
        Source="{Binding Groups}"
        IsSourceGrouped="true"
        ItemsPath="TopItems" />

In my code I do the following:

protected async override void LoadState(Object navigationParameter, ...)
{
    var feedDataSource = (FeedDataSource)navigationParameter;
    this.DefaultViewModel["Groups"] = feedDataSource.Feeds;
}

My FeedDataSource contains an ObservableCollection<FeedCategory> Feeds which has an ObservableCollection<FeedItem> Items and TopItems :

public ObservableCollection<FeedItem> TopItems
{
    get { return new ObservableCollection<FeedItem>(this.Items.Take(5)); }
}

Now - I have added a refresh method which adds more FeedItems to the Items collection however when I refresh, it has no effect on the Grid View on my main page which uses the groupedItemsViewSource for it's ItemsSource property.

ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"

If I navigate away from the page, and then back again (so the page gets rebuilt) the new items are there. Why isn't my GridView showing these changes as they happen? I thought that by binding the collection and grid view they should reflect these changes? I have tried changing them to two one, one way - but it makes no difference.

Can anyone shed some light as to why this isn't working?

like image 444
Terry Avatar asked Aug 19 '12 17:08

Terry


2 Answers

In your TopItems property, you are returning a new ObservableColleciton that contains the first five Items from the Items Collection. The CollectionViewSource is binding to this new ObservableCollection, not to the orginal Items collection. So when you update the Items collection, nothing is bound to it to receive the update notification. You either need to bind to the original Items collection, or, in the method that updates the Items collection with new data, fire a PropertyChanged event for the TopItems property.

like image 140
Jeff Brand Avatar answered Oct 16 '22 16:10

Jeff Brand


You should be able to listen to the CollectionChanged event on the Items ObservableCollection to do what you're asking.

this.Items = new ObservableCollection<FeedItem>();
this.Items.CollectionChanged += delegate { base.OnPropertyChanged("TopItems"); };

Now when the Items collection changes the binding magician will notice that it should also evaluate the TopItems property for changes.

like image 38
Craig Presti - MSFT Avatar answered Oct 16 '22 18:10

Craig Presti - MSFT