WPF + MvvM + 棱镜 [英] WPF + MvvM + Prism
问题描述
我是 Wpf & 的新手Mvvm world ,但我找到了几个例子,只是发现有一些不同的方法来实例化模型.我想知道最好/正确的方法来做到这一点.两种方式都在使用 Unity
I am new in the Wpf & Mvvm world , but I have found a couple of examples and just found that there is some different way to instantiate the model. I would like to know the best/correct way to do it. both ways are using Unity
我吃过的东西:
var navigatorView = new MainView();
navigatorView.DataContext = m_Container.Resolve<INavigatorViewModel>();
m_RegionManager.Regions["NavigatorRegion"].Add(navigatorView);
我做了什么:
var navigatorView = m_Container.Resolve<MainView>;
m_RegionManager.Regions["NavigatorRegion"].Add(navigatorView);
并且我更改了构造函数以接收视图模型,以便我可以将数据上下文指向它:
and I changed the constructor to receive viewmodel so I can point the datacontext to it:
public MainView(NavigatorViewModel navigatorViewModel)
{
this.DataContext = navigatorViewModel;
}
其他例子我发现了另一种方式:
Other examples I've found another way like:
...vm = new viewmodel
...m = new model
v.model = vm;
获取/设置数据上下文
干杯
推荐答案
我喜欢 Igor 的建议,但没有视图模型了解视图.我更喜欢我的依赖项朝一个方向发展(View -> ViewModel -> Model).
I like Igor's suggestion, but without the viewmodel having knowledge of the view. I prefer my dependencies to go one direction (View -> ViewModel -> Model).
我所做的是 ViewModel-First 和 DataTemplate 视图模型.所以我这样做:
What I do is ViewModel-First and just DataTemplate the viewmodel. So I do this:
MainViewModel mainViewModel = container.Resolve<MainViewModel>();
region.Add(mainViewModel, "MainView");
region.Activate(mainViewModel);
添加 ViewModel -> 使用 WPF 数据模板完成的视图映射(不过,我认为 Silverlight 无法实现这种方法)
With the addition of the ViewModel -> View mapping done with a WPF datatemplate (I don't think this approach is possible with Silverlight, though)
应用程序.xaml:
<Application.Resources>
<DataTemplate DataType="{x:Type viewModels:MainViewModel}">
<views:MainView />
</DataTemplate>
</Application.Resources>
就是这样!我喜欢这种方法.我喜欢这种感觉就像魔法一样.它还具有以下优点:
That's it! I love this approach. I like the way it feels like magic. It also has the following advantages:
- 不必修改构造函数以适应映射
- 不必在容器中为 IMyViewModel 注册类型……您可以使用具体类型.我喜欢保留对 IViewRegistry 或 ILogger 等应用服务的注册...诸如此类的事情
- 您可以使用范围限定为某个区域所在的特定视图的资源来更改映射(如果您想重用 ViewModel 但希望它们在应用程序的不同区域中看起来不同,这很好
这篇关于WPF + MvvM + 棱镜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!