开发者

Silverlight & MVVM: Loading data from a web-service in the VM

I am trying to setup the viewModel (VM) to contain the logic to deal with getting the data from a web-service and then load the data into the model, which would then be exposed to the View via the ViewModel.

ViewModel

public StudentViewModel : INotifyPropertyChanged
{
    private List<Student> _students;
    public List<Student> Student
    {
        get{.....}
        set{.....}
    }

    public StudentViewModel()
    {
        //call webservice and load the data into Students
    }    
}

View

set the data-context to the viewModel defined above

<UserControl DataContext=..... />

Problem

Because I am calling the web-service from the ViewModel's ctor, I think the VisualStudio's designer is throwing a fit. Now, I could call a Load method on my VM from the view's PageLo开发者_开发知识库ad method, but I was wondering if there is a better way to handle this problem?

Reason

The reason I am loading students in the CTOR is that I want to display the list of students when view first loads.


You should add a check to the property IsInDesignMode of the DesignerProperties class in your constructor.

If IsInDesignMode returns false you should load your students from your webservice. If you are in DesignMode you could construct dummy objects to initialize your viewmodel with DesignTime data.

public class StudentViewModel : INotifyPropertyChanged{

    public StudentViewModel() {
       if (DesignerProperties.IsInDesignMode) {
         // constructor dummy objects or initialize your viewmodel with DesignTime values
       }
       else {
         // initialize viewmodel with data from webservice
       }


    }

    // rest of the class
  }


Do you use ServiceLocator for creating ViewModels?

I think you can solve your problem by using ServiceLocator. Locator can create new ViewModel object, call (in asynchronous mode) the web service and return the VM. Then in the VM you can have code that will handle complete event of the web service call.

For working with designers you can have in ServiceLocator a code that will call service only if application is in runtime and not in the Visual Studio designer.

Of course I'm not sure if this fits to your program architecture, but it can work.


You could add a test so the service is not invoked when in design mode:

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜