我的环境:VS2022、.Net6.0
【1】先完成基本的环境搭建,可参考 C#-WPF-Prism.DryIoc-【1】环境搭建 - 轻吟浅唱,蓦然花开 - 博客园 (cnblogs.com)
【2】在Views文件夹中添加三个UserControl 分别为View1、View2和View3并分别为三个UserControl添加一个文本控件加以区分
【3】编辑MainView 添加三个按钮用来切换三个View并为这三个按钮绑定命令和参数,添加一个ContentControl承载这三个用户控件
<Window x:Class="Wpf_Prism.DryIoc_Region.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Wpf_Prism.DryIoc_Region.Views" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" mc:Ignorable="d" Title="MainView" Height="450" Width="800"> <DockPanel> <UniformGrid Columns="3" DockPanel.Dock="Top"> <Button Content="打开View1" Command="{Binding OpenViewCommand}" CommandParameter="View1"/> <Button Content="打开View2" Command="{Binding OpenViewCommand}" CommandParameter="View2"/> <Button Content="打开View3" Command="{Binding OpenViewCommand}" CommandParameter="View3"/> </UniformGrid> <!--#region 用来承载 View1 View2 View3 这三个不同的页面--> <ContentControl prism:RegionManager.RegionName="MainContentRegion"/> </DockPanel> </Window>
【4】在App.xaml.cs中添加代码,把View1、View2和View3 分别注册为导航
using Prism.Ioc; using System.Windows; using Wpf_Prism.DryIoc_Region.Views; namespace Wpf_Prism.DryIoc_Region { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { protected override Window CreateShell() { return Container.Resolve<MainView>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<View1>(); containerRegistry.RegisterForNavigation<View2>(); containerRegistry.RegisterForNavigation<View3>(); } } }
【5】编辑MainViewModel.cs 代码如下
using Prism.Commands; using Prism.Regions; namespace Wpf_Prism.DryIoc_Region.ViewModels { public class MainViewModel { private readonly IRegionManager regionManager; public DelegateCommand<string> OpenViewCommand { get; private set; } public MainViewModel(IRegionManager regionManager) { this.regionManager = regionManager; OpenViewCommand = new DelegateCommand<string>(OpenView); } private void OpenView(string obj) { regionManager.Regions["MainContentRegion"].RequestNavigate(obj); } } }
【6】启动项目,运行效果如下
完成,谢谢!