[英]ViewModel and Model and observing changes
Should ViewModels be associated with other ViewModels and interact with them or should only be allowed to interact with Models? 应该将ViewModel与其他ViewModel关联并与其交互,还是应该只允许与Models交互? Or a mix of both? 还是两者兼而有之?
I'll try to be more explicit with code: 我会尝试使用代码更明确:
Is this code OK? 这个代码可以吗?
public class MainViewModel
{
public MainViewModel(IPeopleService service)
{
var people = service.GetPeople();
People = new ObservableCollection<PersonViewModel>(people.Select(p => new PersonViewModel(p)));
}
public ObservableCollection<PersonViewModel> People { get; set; }
public PersonViewModel SelectedPerson { get; set; }
}
You see the SelectedPerson is a ViewModel, not the Model. 您会看到SelectedPerson是ViewModel,而不是Model。
A ViewModel can interact with the other viewmodels , but not the way you did. ViewModel可以与其他ViewModel进行交互,但不能与您进行交互。 In your scenerio MainViewModel depends on PersonViewModel. 在您的场景中,MainViewModel依赖于PersonViewModel。 This is wrong approach and it should be Person model. 这是错误的方法,应该是Person模型。
If you want to interact with ViewModels and transfer data between them, you should use mediator pattern. 如果要与ViewModels交互并在它们之间传输数据,则应使用调解器模式。 Many popular MVVM frameworks have this capability and it's called Messenger service. 许多流行的MVVM框架都具有此功能,称为Messenger服务。
Edit: Here is a sample code. 编辑:这是示例代码。 I generally use MVVM Light, but you can use whatever you want. 我通常使用MVVM Light,但是您可以使用任何您想要的东西。
public class MainViewModel
{
public MainViewModel(IPeopleService service)
{
var people = service.GetPeople();
People = new ObservableCollection<Person>(people.Select(p => new Person(p)));
}
public ObservableCollection<Person> People { get; set; }
private Person _person;
public Person SelectedPerson
{
get
{
return _person;
}
set
{
if(value != null)
{
_person = value;
OnPropertyChanged("SelectedPerson");
//Send selected person on each change
Messenger.Default.Send<Person>(_person);
}
}
}
}
In your PersonViewModel, you should register for messages type of Person: 在您的PersonViewModel中,您应该注册消息类型的Person:
public class PersonViewModel
{
private Person _person;
public Person SelectedPerson
{
get
{
return _person;
}
set
{
if (value != null)
{
_person = value;
OnPropertyChanged("SelectedPerson");
}
}
}
public PersonViewModel()
{
Messenger.Default.Register<Person>(this, (p) =>
{
SelectedPerson = p;
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.