我是MVVM的新手,当我的业务逻辑在父子关系的另一个模型中有一个模型并且我希望我的Views和ViewModel代表它时,我不清楚该怎么做。 意思是我希望子视图独立且可重用(我使用UserControl)并拥有自己的ViewModel和父视图以拥有子元素以及它自己的ViewModel
我能想到的解决方案是在父ViewModel中创建一个包装器,从父模型创建子模型的ViewModel
你能告诉我这是不是意味着什么?或者是否有更好的最佳做法来做到这一点?
这是一个伪代码,我的意思是学生是父母,老师是孩子
//儿童模特 class TeacherModel { public string teacherName {get;组; } }
// The parent model (the student has a teacher)
class StudentModel
{
public int studentId { get; set; }
public TeacherModel teacherModel { get; set; }
}
class TeacherViewModel
{
public TeacherModel teacherModel { get; set; }
}
class StudentViewModel
{
public StudentModel studentModel { get; set; }
// Is this good parctice?
public TeacherViewModel wrapperTeacherViewModel
{
get
{
TeacherViewModel tempTeacherViewModel = new TeacherViewModel();
tempTeacherViewModel.teacherModel = studentModel.teacherModel;
return tempTeacherViewModel;
}
}
}
class TecherView : UserControl
{
//TextBox binded to teacherModel.teacherName using Text="{Binding teacherModel.teacherName}"
}
class StudentView : UserControl
{
// TextBox binded to studentModel.studentId using Text="{Binding studentModel.studentId}"
// Is this good parctice?
// TecherView binded to wrapperTeacherViewModel usinng DataContext="{Binding wrapperTeacherViewModel}"
}
class Porgram
{
void main()
{
TeacherModel teacherModel = new TeacherModel();
teacherModel.teacherName = "Marry";
StudentModel studentModel = new StudentModel();
studentModel.studentId = 12345;
studentModel.teacherModel = teacherModel;
StudentViewModel studentViewModel = new StudentViewModel();
studentViewModel.studentModel = studentModel;
StudentView studentView = new StudentView();
studentView.DataContext = studentView;
}
}
我注意到解决方案存在问题。如果我希望我的内部视图模型(教师)具有模型中不存在的属性,例如“enabled”。那是因为我自己从不创建TeacherViewModel实例,因此我没有机会设置类似teacherViewModel.enabled = false
的内容