我在其他问题中得到了有关如何实现 MVVM 的提示。当学生类本身发生更改时(在我的项目中经常发生这种情况),我在将绑定更新传递给 GUI 时遇到了问题。有没有办法让这些事情变得简单,并以比实施更紧凑的方式实现?或者这是实现 MVVM 的最先进技术?
class MainWindowViewModel : INotifyPropertyChanged
{
ObservableCollection<StudentViewModel> studentViewModels = new ObservableCollection<StudentViewModel>();
public ObservableCollection<StudentViewModel> StudentViewModels
{
get { return studentViewModels; }
}
public MainWindowViewModel()
{
studentViewModels.Add(new StudentViewModel());
studentViewModels.Add(new StudentViewModel());
studentViewModels.Add(new StudentViewModel());
}
public event PropertyChangedEventHandler PropertyChanged;
internal void OnPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
class StudentViewModel : INotifyPropertyChanged
{
Student model;
public String StudentFirstName
{
get { return model.StudentFirstName; }
set { model.StudentFirstName = value; }
}
public String StudentLastName
{
get { return model.StudentLastName; }
set { model.StudentLastName = value; }
}
public StudentViewModel()
{
model = new Student();
this.model.PropertyChanged += (sender, e) =>
{
switch (e.PropertyName)
{
case "StudentFirstName": OnPropertyChanged("StudentFirstName"); break;
case "StudentLastName": OnPropertyChanged("StudentLastName"); break;
default: break;
}
};
}
public StudentViewModel(Student model)
{
this.model = model;
this.model.PropertyChanged += (sender, e) =>
{
switch (e.PropertyName)
{
case "StudentFirstName": OnPropertyChanged("StudentFirstName"); break;
case "StudentLastName": OnPropertyChanged("StudentLastName"); break;
default: break;
}
;
}
public void changeStudent()
{
model.changeStudent();
}
public event PropertyChangedEventHandler PropertyChanged;
internal void OnPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
class Student : INotifyPropertyChanged
{
public String studentFirstName;
public String StudentFirstName
{
get { return studentFirstName; }
set
{
if (studentFirstName != value)
{
studentFirstName = value;
OnPropertyChanged("StudentFirstName");
}
}
}
public String studentLastName;
public String StudentLastName
{
get { return this.studentLastName; }
set
{
if (studentLastName != value)
{
studentLastName = value;
OnPropertyChanged("StudentLastName");
}
}
}
public Student() { }
public void changeStudent()
{
StudentLastName = "McRonald";
}
public event PropertyChangedEventHandler PropertyChanged;
internal void OnPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}