首页 > 其他分享 >Wpf使用Prism的IRegionManager实现页面导航

Wpf使用Prism的IRegionManager实现页面导航

时间:2024-07-14 21:25:40浏览次数:15  
标签:IRegionManager xaml System Windows Prism using Wpf public

Wpf使用Prism的IRegionManager实现页面导航

背景

之前使用winform的形式,利用事件和委托(复杂可以利用反射)实现了wpf的页面跳转。

页面间的导航可以通过使用Prism类库实现,本章节主要讲述这个。

参考内容

文字讲解因为有人做了更好的讲解,所以直接将索引放在下方。但单凭讲解没有完整代码,理解需要更多的时间。特将demo的全部讲解贴在此处。

讲解:Prism区域管理实现导航_regionmanager.registerviewwithregion("lefttreemenu-CSDN博客

实际代码

App.xaml

<prism:PrismApplication x:Class="WPFPrism.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WPFPrism"
             xmlns:prism="http://prismlibrary.com/">
    <Application.Resources>

    </Application.Resources>
</prism:PrismApplication>

App.xaml.cs

using ModuleA;
//using ModuleB;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Modularity;
using System.Windows;
using WPFPrism.Views;

namespace WPFPrism
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        /// <summary>
        /// Creates the shell or main window of the application.
        /// </summary>
        /// <returns></returns>
        protected override Window CreateShell()
        {
            //通过容器去拿MainView,也是启动的地方
            return Container.Resolve<MainView>();
        }

        /// <summary>
        /// Used to register types with the container that will be used by your application.
        /// </summary>
        /// <param name="containerRegistry"></param>
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //依赖注入的功能,增加依赖注入要实现的内容
            //containerRegistry.RegisterForNavigation<ViewA>(); //containerRegistry.RegisterForNavigation<ViewA>("ViewA的具体名字")自定义,可以这样写;
            //containerRegistry.RegisterForNavigation<ViewB>();
            containerRegistry.RegisterForNavigation<ViewC>();//我们依然使用C模块,C模块是当前程序的。
            containerRegistry.RegisterForNavigation<ViewD>();
        }

        /// <summary>
        /// Configures the Prism.Modularity.IModuleCatalog used by Prism.
        /// </summary>
        /// <param name="moduleCatalog"></param>
        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            //这里是走代码的
            //moduleCatalog.AddModule<ModuleAfile>();//加载A模块
            moduleCatalog.AddModule<ModuleBfile>();//加载B模块
            base.ConfigureModuleCatalog(moduleCatalog);
        }

        /// <summary>
        ///  Creates the Prism.Modularity.IModuleCatalog used by Prism.
        /// </summary>
        /// <returns></returns>
        protected override IModuleCatalog CreateModuleCatalog()
        {
            //这里是走配置的
            //return new DirectoryModuleCatalog()
            //{
            //    ModulePath = @"Modules"//这里是主程序exe同文件夹下面的Modules文件夹
            //};
            return base.CreateModuleCatalog();
        }
    }
}

MainViewModel.xaml.cs

using Prism.Commands;   
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFPrism.Views;

namespace WPFPrism.ViewModels
{
    public class MainViewModel : BindableBase
    {
        private readonly IRegionManager regionManager;//区域管理
        private IRegionNavigationJournal journal;//区域导航日志
        public DelegateCommand<string> OpenCommand { get; set; }//创建命令,string用来接收参数,例如ViewA
        public DelegateCommand BackCommand { get; set; }//创建导航上一步命令
        public DelegateCommand ForwardCommand { get; set; }//创建导航下一步命令
        public MainViewModel(IRegionManager regionManager)//这里点击快速操作。拿界面定义的区域Content
        {
            BackCommand = new DelegateCommand(Back);
            ForwardCommand = new DelegateCommand(Forward);
            OpenCommand = new DelegateCommand<string>(Open);
            this.regionManager = regionManager;//拿到这个值
        }

        private void Forward()
        {
            if (journal.CanGoForward)
                journal.GoForward();
        }

        private void Back()//返回上一步方法
        {
            if (journal.CanGoBack)
                journal.GoBack();

        }

        private void Open(string obj)
        {
            NavigationParameters keys = new NavigationParameters();
            keys.Add("Title", "Hello");
            regionManager.Regions["Content"].RequestNavigate(obj, callBack =>
             {
                 if ((bool)callBack.Result)//导航问题
                 {
                     journal = callBack.Context.NavigationService.Journal;
                 }
             }, keys);//这里需要依赖注入的方式
        }
    }

}

MainView.xaml

<Window x:Class="WPFPrism.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:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        xmlns:local="clr-namespace:WPFPrism"
        mc:Ignorable="d"
        Title="MainView" Height="450" Width="800">
    <!--自动关联AutoWireViewModel-->
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition />
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" >
            <Button Content="打开模块A" Margin="5" Command="{Binding OpenCommand}" CommandParameter="ViewA"/>
            <Button Content="打开模块B" Margin="5" Command="{Binding OpenCommand}" CommandParameter="ViewB"/>
            <Button Content="打开模块C" Margin="5" Command="{Binding OpenCommand}" CommandParameter="ViewC"/>
            <Button Content="打开模块D" Margin="5" Command="{Binding OpenCommand}" CommandParameter="ViewD"/>
            <Button Content="返回上一步" Margin="5" Command="{Binding BackCommand}" />
            <Button Content="返回下一步" Margin="5" Command="{Binding ForwardCommand}" />
        </StackPanel>
        <ContentControl Grid.Row="1" prism:RegionManager.RegionName="Content" />
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFPrism.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainView : Window
    {
        public MainView()
        {
            InitializeComponent();
        }
    }
}

ViewC.xaml

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFPrism.Views
{
    /// <summary>
    /// ViewC.xaml 的交互逻辑
    /// </summary>
    public partial class ViewC : UserControl
    {
        public ViewC()
        {
            InitializeComponent();
        }
    }
}
<UserControl x:Class="WPFPrism.Views.ViewC"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WPFPrism.Views"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800" Background="Orange">
    <Grid>
        <TextBlock Text="我 是 C" FontSize="50"/>
    </Grid>
</UserControl>

ViewD.xaml

<UserControl x:Class="WPFPrism.Views.ViewD"
        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:WPFPrism.Views"
        mc:Ignorable="d" Height="450" Width="800" Background="Green">
    <Grid>
        <TextBlock Text="我 是 D" FontSize="50"/>
    </Grid>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WPFPrism.Views
{
    /// <summary>
    /// ViewD.xaml 的交互逻辑
    /// </summary>
    public partial class ViewD : UserControl
    {
        public ViewD()
        {
            InitializeComponent();
        }
    }
}

ViewAViewModel.cs

using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ModuleA.ViewModels
{
    public class ViewAViewModel : BindableBase, IConfirmNavigationRequest  //INavigationAware  //IConfirmNavigationRequest导航离开的时候,进行判断提示
    {
        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; RaisePropertyChanged(); }
        }

        public ViewAViewModel()
        {
            //执行顺序1
        }
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            //每次重新重新导航的时候,是否重用原来的实例
            return true;
        }


        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            //在导航离开时调用。
        }

        /// <summary>
        /// 当已导航到实现时调用。
        /// </summary>
        /// <param name="navigationContext"></param>
        public void OnNavigatedTo(NavigationContext navigationContext)
        {

            //执行顺序2
            if (navigationContext.Parameters.ContainsKey("Title"))//判断是否有值再赋值
            {
                Title = navigationContext.Parameters.GetValue<string>("Title");
            }
        }

        public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
        {
            //导航离开的时候,进行判断提示,是否允许从A到B模块

            bool b = true;
            if (MessageBox.Show("确定切换吗", "提示", MessageBoxButton.YesNo) == MessageBoxResult.No)
                b = false;
            continuationCallback(b);
        }
    }
}

ViewA.xaml

<UserControl x:Class="ModuleA.Views.ViewA"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:ModuleA.Views"
                     xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800" Background="Red">
    <Grid>
        <TextBlock Text="我是A" FontSize=" 30"/>
        <TextBlock Margin="50" Text="{Binding Title}" FontSize=" 30"/>
    </Grid>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ModuleA.Views
{
    /// <summary>
    /// ViewsA.xaml 的交互逻辑
    /// </summary>
    public partial class ViewA : UserControl
    {
        public ViewA()
        {
            InitializeComponent();
        }
    }
}

ModuleAfile.cs

using ModuleA.ViewModels;
using ModuleA.Views;
using Prism.Ioc;
using Prism.Modularity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ModuleA
{
    public class ModuleAfile : IModule

    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
            //初始化
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //依赖注入,模块注册。和主程序继承PrismApplication类似。
            containerRegistry.RegisterForNavigation<ViewA,ViewAViewModel>();//进行匹配,这里一般不使用自动匹配
        }
    }
}

好了,分享就到这里。

标签:IRegionManager,xaml,System,Windows,Prism,using,Wpf,public
From: https://blog.csdn.net/yannsann/article/details/140423206

相关文章

  • WPF generate rows and columns via C# dynamically
    //xaml<Windowx:Class="WpfApp214.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......
  • WPF Canvas ZoomIn ZoomOut via set Background="Transparent"
    <CanvasGrid.Column="1"Background="Transparent"x:Name="cvs"ClipToBounds="True"MouseWheel="cvs_MouseWheel"MouseDown="cvs_MouseDown"MouseUp="cvs_MouseUp"MouseMove="cvs_......
  • WPF canvas locate
    //xaml<Windowx:Class="WpfApp210.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.mi......
  • 在WPF中使用WriteableBitmap对接工业相机及常用操作
    写作背景写这篇文章主要是因为工业相机(海康、大恒等)提供的.NET开发文档和示例程序都是用WinForm项目来说明举例的,而在WPF项目中对图像的使用和处理与在WinForm项目中有很大不同。在WinForm中用System.Drawing.Bitmap来处理图像,而在WPF中是用System.Windows.Media.Imaging.Writeab......
  • WPF中style的应用(小白快速上手)
    1.解释说明    -通过设置style资源词典可以批量设置控件,不仅节省大量时间,还能方便统一修改    -重复利用Border这个控件,可以自由设计新的控件风格    -这里要注意,虽然style也是写在xaml文件中,但是其文件类型为资源词典类型,这里程序示例也进行不......
  • 优质WPF免费学习资源分享(含代码)
    WPF自学资源分享背景自身是winform开发,winform岗位比较少。wpf和winfom殊途同归,所以自身最近也在学习wpf。分享一下自己寻找到的wpf学习资源,希望对大家有帮助。学习资源推荐书籍学习资源《深入简出WPF》-刘铁猛作者是微软的高级开发工程师,多年的wpf开发经验。不过作者......
  • WPF开源的一款免费、开箱即用的翻译、OCR工具
    思维导航前言WPF介绍工具快捷键工具下载工具部分功能截图项目源码地址优秀项目和框架精选DotNetGuide技术社区交流群前言今天大姚给大家分享一款由WPF开源的、免费的(MITLicense)、即开即用、即用即走的翻译、OCR工具:STranslate。WPF介绍WPF是一个强大的桌面应......
  • 【WPF控件样式】
    自定义弹窗单选框CheckBox扁平化<Stylex:Key="CheckBoxStyle1"TargetType="{x:TypeCheckBox}"><SetterProperty="BorderThickness"Value="1"/><SetterProperty="Template"><Setter.V......
  • WPF中引用不到相对路径图片?
    在wpf中使用相对路径运行项目时却不显示图片怎么解决?新建img文件夹添加所需要的图片选中图片右键属性设置属性重新生成即可运行效果转载请标明出处!......
  • WPF WebBrowser navigate to website via url and escape script error warning
    Copyfrom https://www.iditect.com/faq/csharp/wpf-webbrowser-control--how-to-suppress-script-errors.html#:~:text=To%20suppress%20these%20script%20errors%2C%20you%20can%20handle,using%20the%20Cancel%20property%20of%20the%20WebBrowserNavigatingEventArgs%20pa......