user1572130
user1572130

Reputation: 65

How to update the Gridview?

im writing an Windows Store Application.
I have an View(FavoritenGrid) with an GridView. This View works with a DataContext(FavoritenViewModel). And the DataContext has a List(FavList).

Now i want to get the latest FavList when i load the View.

Code snippets:

public FavoritenGrid()
{
    this.InitializeComponent();
    _vm = ((FavoritenViewModel)this.DataContext);
     ((DataViewModel)this.DataContext).LoadDataCommand.Execute(null);
    groupedItemsViewSource.Source =  _vm.FavList;
    (semanticZoom.ZoomedOutView as ListViewBase).ItemsSource = groupedItemsViewSource.View.CollectionGroups;
}

FavoritenViewModel List

 private ObservableCollection<FavoritenGroup<Draggable>> _favList;

public ObservableCollection<FavoritenGroup<Draggable>> FavList
{
    get { return _favList; }
    set
    {
        _favList = value;
        RaisePropertyChanged("FavList");
    }
}

FavoritenViewModel Loading method

 private async Task loadData()
 {
    IsLoading = true;

    FavList =  new ObservableCollection<FavoritenGroup<Draggable>>();
    FavList = await getFavoriten();

    IsLoading = false;
 }

If i dont initialize the List with an empty List i get a NullPointerException.

FavList =  new ObservableCollection<FavoritenGroup<Draggable>>();

This method loads the latest FavList. But its not shown in the View, i have to leave the View and load it again to see the changes.

FavList = await getFavoriten();

Upvotes: 0

Views: 588

Answers (1)

ZombieSheep
ZombieSheep

Reputation: 29963

Your view won't update in this instance because the ObservableCollection is not being updated, it is being replaced.

If I were you, I would do the following.

FavoritenViewModel

private ObservableCollection<FavoritenGroup<Draggable>> _favList = new ObservableCollection<FavoritenGroup<Draggable>>();
public ObservableCollection<FavoritenGroup<Draggable>> FavList
{
    get { return _favList; }
    set
    {
        _favList = value;
        RaisePropertyChanged("FavList");
    }
}

and then remove the FavList = new ObservableCollection<FavoritenGroup<Draggable>>(); in the loadData() method.

Next, when you are updating your list, instead of creating a new collection (thereby replacing your ObservableCollection) I'd try to remove items that don't exist any more, and add new ones if they are not already on the list. (You could Clear() the items, and then add all your new ones. This will update the existing collection and should fire the event to update the UI.

Upvotes: 1

Related Questions