开发者

Binding to ObservableCollection with MVVM Light

I have a MainViewModel that contains a reference to an ObservableCollection:

public ObservableCollection<SomeClass> Li开发者_JAVA技巧stOfPeople
{
    get
    {
        return MyClass.BaseCollection;
    }
}

BaseCollection is also an instance of ObservableCollection<SomeClass>. ListOfPeople is bound to a ListBox control on the second page - the application starts with the first page, initiates the download process to populate BaseCollection and switches to the second page while the download is still in progress.

The problem is that when the binding occurs, BaseCollection is null and therefore the ListBox is not populated. However, even when the download process finishes, the ListBox still remains empty. I am assuming this is happening because BaseCollection isn't notifying the proper instance about existing changes to the collection, but I am not sure.

BaseCollection has items inside it - I confirmed it.

Any suggestions on how I can work around the issue? Anyone here binding to an ObservableCollection via MVVM Light just like I showed above?


If you donot want to instantiate an empty ListOfPeople in the constructor and use this instance for database-loading you have to do this:

After loading of ListOfPeople is completed, your MainViewModel must call RaisePropertyChanged("ListOfPeople"); to tell the view that the data has changed.

Background: Thanks to ObservableCollection MyClass.BaseCollection.Add() updates the gui. As soon as MyClass.BaseCollection = new Obser... is called there is no more update of the gui since the gui holds a reference to the old contend of MyClass.BaseCollection. mvvm-light-RaisePropertyChanged() tells the gui to update its reference to a new collection


I haven't worked on MVVM Light, so sorry if there is something specific about it that i am missing.

Looking at your implementation,

public ObservableCollection<SomeClass> ListOfPeople
{
    get
    {
        return MyClass.BaseCollection;
    }
}

This code should work, and the control which is binded to this source should get propert updated without being concerned about the actual source where the instance of observable is created.

Thus, the only possible problem here could be that your MyBase.BaseCollection is null in the begining. So, if you avoid that situation and create an empty collection where you have declared this observable item, and then trigger your downloading process the way it is, then everything should work fine.

Hope this would be of help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜