WPF 中的一个视图可以有多个 ViewModel吗
WPF 中的一个视图可以有多个 ViewModel 吗?因为有时我们只需要以简单视图格式显示视图,有时同一视图必须以可编辑格式显示。因此我们可以为每个创建单独的视图模型。
那么有没有办法将 2 个不同的视图模型挂接到一个视图上呢?
Can I have multiple ViewModel for a View in WPF? Because some times we need to show the view only in simple view format and sometimes the same view has to shown in editable format. Hence we can create seperate view models for each.
So is there any way to hook 2 diffrent view models to a view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ViewModel 应该充当视图的数据上下文,因此只允许单个虚拟机。
您没有理由不将 View 分解为多个 UserControl,每个 UserControl 都有自己的 ViewModel。
A ViewModel should serve as the Data Context for your View, so that would only allow a single VM.
There is no reason why you could not break you View up in to multiple UserControls, each with their own ViewModel.
通常,您会将视图绑定到单一类型的视图模型。这并不是说您的类型不能是接口或两个视图都继承自的基类。
当我有一个要跨越多个不同视图的视图模型类型时,我倾向于仅使用接口或基/派生类情况。例如,如果我有两种不同类型的表单来显示小部件信息,我将创建一个基本的小部件 ViewModel 类。
就您的情况而言,听起来您应该 a.) 为简单视图和高级视图创建两个视图,或者 b.) 只需使用单个 ViewModel 类。
Generally you're going to bind your View to a single type of View Model. That's not to say that your type couldn't be an interface, or a base class from which both of your views inherit.
I tend to only use an interface or base/derived class situation when I have a single view model type that is going to span several different views. For example if I have two different types of forms that display widget information, I would create a single base Widget ViewModel class.
In your case, it sounds you should either a.) create two views for your simple and advanced views or b.) simply use a single ViewModel class.