我是MVVM实现的新手.这可能听起来像是一个重复的问题,但我找不到什么能帮助我更好地理解我的基本知识.我有一个Model有成员的班级,如下所示:
public class Model
{
public string Name { get; set; }
public int Age { get; set; }
public List<Model> Children { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我已将此模型类包装在视图模型中,但ObservableCollection代替了List.
public class ViewModel
{
private Model model;
public ViewModel()
{
model = new Model();
}
//getters and setters for both Name and Age
public ObservableCollection<ViewModel> Children
{
//how to convert List<Model> to ObservableCollection<ViewModel> here?
}
}
Run Code Online (Sandbox Code Playgroud)
我绝对不希望将我的Model类暴露给视图,这就是我需要创建ObservableCollectionVM类的原因.不知道如何实现这一目标.任何帮助赞赏.
您可能正在寻找以下内容:
public class Model
{
public string Name { get; set; }
public int Age { get; set; }
public List<Model> Children { get; set; }
}
public class ViewModel
{
public ViewModel(Model m)
{
Name = m.Name;
Age = m.Age;
Children = new ObservableCollection<ViewModel>(m.Children.Select(md=>new ViewModel(md)));
}
public string Name { get; set; }
public int Age { get; set; }
public ObservableCollection<ViewModel> Children { get; set; }
public Model GetModel()
{
return new Model()
{
Age = Age,
Name = Name,
Children = Children.Select(vm=>vm.GetModel()).ToList(),
};
}
}
Run Code Online (Sandbox Code Playgroud)
您会注意到很多是样板代码.但是如果你这样做,你的模型/视图模型是完全分开的,这将为你节省很多问题.
| 归档时间: |
|
| 查看次数: |
690 次 |
| 最近记录: |