E-Bat
E-Bat

Reputation: 4892

Implementing MVVM in Silverlight: Asynchronous execution issue

Hi i'm facing a problem and cannot find a suitable solution for it. In my View i have severals Combobox which neeed to be populated from Viewmodel. DataContent for the View is defined like this:

<navigation:Page.Resources>
    <viewModel:TheViewModel x:Key="viewModel"/>
</navigation:Page.Resources>

<navigation:Page.DataContext>
    <Binding Source="{StaticResource viewModel}"/>
</navigation:Page.DataContext>

Then in ViewModel constructor i have code like the following:

LoadOperation<ProducType> loadPT = context.Load(context.GetProducTypeQuery());
    loadPT.Completed += (sender1, e1) => {
        if (!loadPT.HasError) {
            LoadOperation<Client> loaC = context.Load(context.GetClientQuery());
                loaC .Completed += (sender2, e2) => {
                    if (!loaC.HasError) {
                        ProducTypes = loadPT.Entities;
                        Clients= loaC.Entities;   
                        Remitentes = loadr.Entities;
                     }
                  };
         }
    };

With this configuration i have a problem that my comboboxes never get populated because wof the Asynchronous model of Silverlight, when the framework finished creating the view the code above is not executed yet. I'm sure this must be some lack of knowledge on my part, i'm not new in porgamming but very new in silverlight, any help please will be appreciated Thanx Elio

Upvotes: 1

Views: 244

Answers (1)

Dave Swersky
Dave Swersky

Reputation: 34810

My ViewModels derive from a base class that implements INotifyPropertyChanged. I bind my comboboxes to public properties on my ViewModel. Put the async call to get the data in the property getters.

Here's an example:

ViewModel:

public class MyViewModel : BaseViewModel
{
    private List<MyObject> _myObjectlist;
    public List<MyObject> MyObjectList
    {
         get
         {
             if (_myObjectList == null)
             {
                  _ctx.Load(q=>{
                        _myObjectList = q.Value;
                        //INotifyPropertyChanged implementation
                        RaisePropertyChanged("MyObjectList"); 
                   },null);
             }
         }
    }
}

Upvotes: 1

Related Questions