Silverlight&;MVVM:从VM中的web服务加载数据
我试图设置viewModel(VM),以包含处理从web服务获取数据的逻辑,然后将数据加载到模型中,然后通过viewModel将数据公开给视图 视图模型Silverlight&;MVVM:从VM中的web服务加载数据,silverlight,mvvm,Silverlight,Mvvm,我试图设置viewModel(VM),以包含处理从web服务获取数据的逻辑,然后将数据加载到模型中,然后通过viewModel将数据公开给视图 视图模型 public StudentViewModel : INotifyPropertyChanged { private List<Student> _students; public List<Student> Student { get{.....} set{...
public StudentViewModel : INotifyPropertyChanged
{
private List<Student> _students;
public List<Student> Student
{
get{.....}
set{.....}
}
public StudentViewModel()
{
//call webservice and load the data into Students
}
}
public StudentViewModel:INotifyPropertyChanged
{
私立大学学生名单;
公开名单学生
{
获取{…}
集合{…}
}
公共学生视图模型()
{
//调用webservice并将数据加载到学生中
}
}
查看
将数据上下文设置为上面定义的viewModel
<UserControl DataContext=..... />
问题
因为我是从ViewModel的ctor调用web服务的,所以我认为VisualStudio的设计师是在大发雷霆。
现在,我可以从视图的PageLoad方法调用VM上的Load方法,但是我想知道是否有更好的方法来处理这个问题
原因
我在CTOR中加载学生的原因是,我想在首次加载视图时显示学生列表。是否使用ServiceLocator创建视图模型 我认为使用ServiceLocator可以解决您的问题。定位器可以创建新的ViewModel对象,调用(在异步模式下)web服务并返回VM。然后在VM中,您可以拥有处理web服务调用的完整事件的代码 对于使用设计器,您可以在ServiceLocator中使用代码,该代码仅在应用程序处于运行时而不在Visual Studio设计器中时调用服务
当然,我不确定这是否适合您的程序架构,但它可以工作。您应该在构造函数中为类的属性IsInDesignMode添加一个检查 如果IsInDesignMode返回false,则应从Web服务加载学生。如果处于设计模式,则可以构造虚拟对象以使用设计时间数据初始化viewmodel
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
}
您可以添加测试,以便不调用服务: