1. 为什么需要模块化导航?
在传统的WPF开发中,我们经常会遇到一个头疼的问题:界面逻辑和业务代码搅在一起,就像一碗打翻的意大利面,越搅越乱。我接手过一个项目,MainWindow.xaml.cs文件里有2000多行代码,每次改个按钮位置都得小心翼翼,生怕碰坏了其他功能。这种紧耦合的架构让团队吃尽了苦头。
Prism框架给出的解决方案是把应用拆分成独立的模块。想象你的应用是个乐高玩具,每个功能模块就像一块积木,可以单独开发、测试,最后通过导航机制拼装起来。RegionManager就是这个拼装师,它负责在指定区域动态加载不同视图,而ViewModel之间完全不需要知道彼此的存在。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境搭建与基础配置
2.1 创建Prism项目
首先打开Visual Studio(建议2019或更高版本),选择"WPF应用(.NET Framework)"模板。这里有个坑要注意:一定要选.NET Framework 4.6.1以上版本,因为Prism 7.2开始需要这个基础运行时。
安装NuGet包时别手抖,这三个是核心依赖:
- Prism.Core
- Prism.Wpf
- Prism.Unity(如果用其他DI容器就选对应的包)
我习惯用Package Manager Console安装:
powershell复制Install-Package Prism.Wpf -Version 7.2.0.1422
Install-Package Prism.Unity -Version 7.2.0.1422
2.2 改造应用启动流程
删除自动生成的MainWindow.xaml后,重点改造App.xaml。把根节点改成这样:
xml复制<prism:PrismApplication x:Class="YourApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/">
</prism:PrismApplication>
后台代码需要重写三个关键方法:
csharp复制protected override Window CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
// 这里注册视图导航映射
containerRegistry.RegisterForNavigation<ViewA>("ViewA");
containerRegistry.RegisterForNavigation<ViewB>(
