Prism(四) 视图模型定位器

源码地址 - WineMonk/PrismStudy: Prism框架学习 (github.com)

视图模型定位器

在 Prism 中,视图模型定位器(ViewModelLocator)是一种设计模式,用于自动将视图(View)和视图模型(ViewModel)进行关联。这种关联是通过在 XAML 中使用特定的命名约定来实现的,而不需要显式地指定视图模型。

Prism 的视图模型定位器通常使用 XAML 的附加属性(Attached Properties)来实现。这些附加属性告诉 Prism 在加载视图时,应该使用哪个视图模型。

以下是一个简单的示例,展示了如何在 Prism 中使用视图模型定位器:

1
2
3
4
5
6
7
8
9
<UserControl x:Class="MyNamespace.Views.MyView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
<!-- Content of the view -->
</Grid>
</UserControl>

在上面的示例中,prism:ViewModelLocator.AutoWireViewModel="True" 是视图模型定位器的关键部分。它告诉 Prism 自动将该视图与其对应的视图模型关联起来。Prism 会根据视图的名称(如 MyView),查找与之对应的视图模型(例如 MyViewModel),然后自动创建并关联它们。

需要注意的是,为了使视图模型定位器正常工作,视图模型类的名称必须符合一定的命名约定,通常是将视图的名称加上 “ViewModel” 后缀,且在 ViewModelsViews 后的相对命名空间路径需要保持一致

这种自动关联视图和视图模型的方式,可以减少重复的代码,提高开发效率,同时也使得代码更加清晰和易于维护。

image-20240304134135220

自定义视图模型定位器

在不使用约定命名规范时,可在代码中自定义注册视图与视图模型。

App.xaml.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public partial class App : PrismApplication
{
protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{

}

protected override void ConfigureViewModelLocator()
{
base.ConfigureViewModelLocator();

// type / type
//ViewModelLocationProvider.Register(typeof(MainWindow).ToString(), typeof(CustomViewModel));

// type / factory
//ViewModelLocationProvider.Register(typeof(MainWindow).ToString(), () => Container.Resolve<CustomViewModel>());

// generic factory
//ViewModelLocationProvider.Register<MainWindow>(() => Container.Resolve<CustomViewModel>());

// generic type
ViewModelLocationProvider.Register<MainWindow, CustomViewModel>();
}
}