MVVM从viewModel访问其他视图的元素
我开始在一个新项目中使用 MVVM 模式。 一切都很好,但我遇到了以下问题。 实现如下所示: 我有一个 MainView,主应用程序窗口。在此窗口中,我有一个 telerik RadGroupPanel,其中我将其余的应用程序视图托管为选项卡。 其余的 viewModel 不知道托管在 MainVIew 中的 RadGroupPanel。 我应该如何从 viewModels 中的命令正确地将这些视图添加到 RadGroupPanel 中? 谢谢。
I started working with the MVVM pattern in a new project.
Everything is ok, but i came to the following problem.
The implementation looks like this:
I have a MainView, the main app window. In this window i have a telerik RadGroupPanel in wich I host the rest of the app views as tabs.
The rest of the viewModels does not know about this RadGroupPanel which is hosted in MainVIew.
How should i correctly add those views to the RadGroupPanel from the commands in the viewModels?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否考虑过使用接口将视图注入到 ViewModel 中以保持分离?我知道这会破坏 MVVM,但我已经在许多 WPF 项目中成功使用了它。我称之为 MiVVM或模型接口到视图ViewModel。
图案很简单。您的用户控件应该有一个界面,称之为 IView。然后在 ViewModel 中你有一个带有 IMyView 类型的 setter 的属性,比如
然后在视图中创建一个名为 This 的依赖属性,
最后在 Xaml 中你可以使用绑定将视图直接注入到 ViewModel 中
尝试一下出去!我已经多次使用这种模式,并且您可以在启动时获得注入一次视图的接口。这意味着您可以保持分离(可以测试 Viewmodel,因为可以模拟 IView),但您可以解决许多第三方控件缺乏绑定支持的问题。另外,它的速度很快。您知道绑定使用反射吗?
上面的博客链接中有一个演示项目展示了这种模式。如果您使用第三方控件,我建议尝试 MiVVM 的附加属性实现。
Have you considered injecting your view into the ViewModel using an interface to maintain separation? I know this breaks MVVM but I've successfully used this on a number of WPF projects. I call it MiVVM or Model Interface-to-View ViewModel.
The pattern is simple. Your Usercontrol should have an interface, call it IView. Then in the ViewModel you have a property with a setter of type IMyView, say
Then in the view you create a dependency property called This
finally in Xaml you can inject the view directly into the ViewModel using binding
Try it out! I've used this pattern many times and you get an interface to the view injected once on startup. This means you maintain separation (Viewmodel can be tested as IView can be mocked), yet you get around the lack of binding support in many third party controls. Plus, its fast. Did you know binding uses reflection?
There's a demo project showcasing this pattern on the blog link above. I'd advocate trying out the Attached Property implementation of MiVVM if you are using a third party control.
您可以在 ObservableCollection 在主窗口视图模型中。然后,您可以将 RadGroupPanel 的 ItemsSource 绑定到该集合,并使用 RadGroupPanel 的 ItemTemplateSelector 和 ContentTemplateSelector 根据绑定的视图模型选择要使用的正确模板。
You can have the list of viewmodels that you need to add controls for in an ObservableCollection in your main window viewmodel. You can then bind the ItemsSource of the RadGroupPanel to that collection and use the ItemTemplateSelector and ContentTemplateSelector of the RadGroupPanel to select the right template to use based on the viewmodel that is bound.