WPF MVVM:ViewModel 如何相互通信?
我有一个视图,上面有 2 个子视图,并且为每个视图分配了一个 ViewModel:
ViewA - ViewModelA
{
ViewB - ViewModelB
ViewC - ViewModelC
}
ViewB 有一个文本框,ViewC 有一个组合框,这两个视图我都需要从 ViewModelA 访问。不是 GUI 控件本身,而是绑定值,即文本框的 .Text 和 ComboBox 的 .SelectedItem。目前我只有 ViewModelB 和 ViewModelC 作为 ViewModelA 的属性,但感觉不对。
视图模型在不破坏 MVVM 模式的情况下相互通信的标准方式是什么?
I have a View which has 2 sub views on it and a ViewModel is assigned to each view:
ViewA - ViewModelA
{
ViewB - ViewModelB
ViewC - ViewModelC
}
ViewB has a text box and ViewC has a combobox, both of which i need access from ViewModelA. Not the GUI control itself, but the bound value i.e. .Text of the textbox and .SelectedItem of the ComboBox. Currently i just have ViewModelB and ViewModelC as properties on ViewModelA but it feels wrong.
What's the standard way for view models to communicate with each other without breaking the MVVM pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让断开连接的 ViewModel 相互通信的一种方法是使用发布/订阅机制,例如 PRISM 的 事件聚合器。但是,在父/子 ViewModel 关系中,我认为父级可以直接了解并控制子 ViewModel。
就我个人而言,我不认为从其他 ViewModel 中组合出一个 ViewModel 是一种不好的做法。我一直这样做。 在我的 ViewModel 中,我通常更喜欢组合而不是继承。
One way to have disconnected ViewModels communicate to each other is to use a publish / subscribe mechanism such as PRISMs EventAggregator. However, in a parent / child ViewModel relationship, I think it's fine for the parent to have direct knowledge and control over the child ViewModel.
Personally, I don't think composing a ViewModel out of other ViewModels is a bad practice. I do it all the time. I generally favor composition over inheritance in my ViewModels.
ViewModel 通常从 Model 中“继承”关系。当有意义的时候添加一个关系并没有错。
ViewModel 拥有引用另一个 ViewModel 的属性是完全可以的。
The ViewModels usually 'inherit' relationships from the Model. And it's not wrong to add a relation when it makes sense.
It's perfectly OK for a ViewModel to have a property referring to another ViewModel.