prism WPF 对话框

项目结构

1.创建对话框 用户控件

Views \ DialogView.xaml

复制代码
<UserControl x:Class="PrismWpfApp.Views.DialogView"
             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:PrismWpfApp.Views"
             mc:Ignorable="d" 
             d:DesignHeight="200" d:DesignWidth="400">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>

        <TextBlock Grid.Row="0" Text="温馨提示"></TextBlock>
        <TextBlock Grid.Row="1" Text="{Binding Msg}"></TextBlock>
        <StackPanel Grid.Row="2" Orientation="Horizontal">
            <Button Content="确定" Command="{Binding ConfirmCommand}" ></Button>
            <Button Content="取消" Command="{Binding ConcelCommand}" ></Button>
        </StackPanel>
    </Grid>
</UserControl>

ViewModels \ DialogViewModel.cs

这里要注意一定要IDialogAware实现这个接口

复制代码
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PrismWpfApp.ViewModels
{
    /// <summary>
    /// 对话框 服务 Model
    /// </summary>
    public class DialogViewModel : BindableBase, IDialogAware
    {
        private string _mag;

        public string Msg
        {
            get { return _mag; }
            set
            {
                SetProperty(ref _mag, value);
            }
        }

        private string _userId;

        public string UserId
        {
            get { return _userId; }
            set
            {
                SetProperty(ref _userId, value);
            }
        }

        public string Title => "这是对话框的标题";

        /// <summary>
        /// 关闭 委托
        /// </summary>
        public event Action<IDialogResult> RequestClose;

        /// <summary>
        /// 是否能关闭对话框
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool CanCloseDialog()
        {
            return true;
        }

        /// <summary>
        /// 关闭后要处理的逻辑
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void OnDialogClosed()
        {
            //关闭也可以传参数(但一般不这么做)
            DialogParameters pairs = new DialogParameters();
            pairs.Add("Result", 0);

            //RequestClose 不为null时执行
            RequestClose?.Invoke(new DialogResult(ButtonResult.No, pairs));

            //两种方法等效
            //if (RequestClose != null)
            //{
            //    RequestClose.Invoke(new DialogResult(ButtonResult.No));
            //}
        }

        /// <summary>
        /// 打开对话框前的处理逻辑
        /// </summary>
        /// <param name="parameters"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters.ContainsKey("Msg"))
            {
                Msg = parameters.GetValue<string>("Msg");
            }
            if (parameters.ContainsKey("UserId"))
            {
                UserId = parameters.GetValue<string>("UserId");
            }
        }

        /// <summary>
        /// 确定 命令
        /// </summary>
        public DelegateCommand<string> ConfirmCommand
        {
            get
            {
                return new DelegateCommand<string>((arg) =>
                {
                    DialogParameters pairs = new DialogParameters();
                    pairs.Add("Result", 1);
                    pairs.Add("Msg", "成功");

                    //RequestClose 不为null时执行
                    RequestClose?.Invoke(new DialogResult(ButtonResult.OK, pairs));
                });
            }
        }

        /// <summary>
        /// 取消 命令
        /// </summary>
        public DelegateCommand<string> ConcelCommand
        {
            get
            {
                return new DelegateCommand<string>((arg) =>
                {
                    //RequestClose 不为null时执行
                    RequestClose?.Invoke(new DialogResult(ButtonResult.No));
                });
            }
        }
    }
}

3.注册 对话框服务

App.xaml.cs

复制代码
using Prism.Ioc;
using Prism.Modularity;
using Prism.Unity;
using PrismWpfApp.ViewModels;
using PrismWpfApp.Views;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace PrismWpfApp
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : PrismApplication
    {
        /// <summary>
        /// 提供主窗口的对象
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        protected override Window CreateShell()
        {
            //打开第一个窗口 ModuleWindow
            //return Container.Resolve<MainWindow>();
            return Container.Resolve<ModuleWindow>();
            //return new MainWindow();
        }

        /// <summary>
        /// 业务中所有需要注入的对象,在这个方法里注册
        /// </summary>
        /// <param name="containerRegistry"></param>
        /// <exception cref="NotImplementedException"></exception>
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //注册 导航 RegisterForNavigation
            containerRegistry.RegisterForNavigation<UserControlA>();
            containerRegistry.RegisterForNavigation<UserControlB>();
            containerRegistry.RegisterForNavigation<UserControlC>();

            //注册 对话框服务
            containerRegistry.RegisterDialog<DialogView, DialogViewModel>();
        }

        /// <summary>
        /// 添加模块(代码引用)
        /// </summary>
        /// <param name="moduleCatalog"></param>
        //protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        //{
        //    moduleCatalog.AddModule<ModuleAProfile>();
        //    moduleCatalog.AddModule<ModuleBProfile>();
        //    base.ConfigureModuleCatalog(moduleCatalog);
        //}

        /// <summary>
        /// 创建模块
        /// </summary>
        protected override IModuleCatalog CreateModuleCatalog()
        {
            return new DirectoryModuleCatalog() { ModulePath = @".\Modules" };
        }

        //protected override void OnStartup(StartupEventArgs e)
        //{
        //    base.OnStartup(e);

        //    if (new LoginWindow().ShowDialog() == true)
        //    {
        //        new MainWindow().ShowDialog();
        //    }
        //    Application.Current.Shutdown();
        //}
    }
}

4.增加打开对话框服务 的按钮

ModuleWindow.xaml

复制代码
<Window x:Class="PrismWpfApp.Views.ModuleWindow"
        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:PrismWpfApp.Views"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        mc:Ignorable="d"
        Title="{Binding Title}" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition ></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <Button Content="模块1" Width="80" Height="30" Command="{Binding ShowContentCommand}" CommandParameter="UserControl1" ></Button>
            <Button Content="模块2" Width="80" Height="30" Command="{Binding ShowContentCommand}" CommandParameter="UserControl2" ></Button>
            <Button Content="后退" Width="80" Height="30" Command="{Binding BackCommand}" ></Button>
            <Button Content="打开对话框" Width="80" Height="30" Command="{Binding ShowDialogCommand}" CommandParameter="DialogView" ></Button>
        </StackPanel>

        <ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegions"></ContentControl>
    </Grid>
</Window>

ModuleWindowViewModel.cs

复制代码
using Prism.Commands;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace PrismWpfApp.ViewModels
{
    public class ModuleWindowViewModel : UiViewModelBase
    {
        /// <summary>
        /// Prism 提供 区域管理接口
        /// </summary>
        private readonly IRegionManager _regionManager;

        public ModuleWindowViewModel(IRegionManager regionManager, IDialogService dialogService)
        {
            this.Title = "XXX系统";
            _regionManager = regionManager;
            _dialogService = dialogService;
        }

        /// <summary>
        /// 记录上一步(导航记录)
        /// </summary>
        private IRegionNavigationJournal _navigationJournal;

        /// <summary>
        /// 对话框服务
        /// </summary>
        private readonly IDialogService _dialogService;

        /// <summary>
        /// 显示区域内容
        /// </summary>
        public DelegateCommand<string> ShowContentCommand
        {
            get
            {
                return new DelegateCommand<string>((arg) =>
                {
                    // 打开 区域、模块
                    //_regionManager.Regions["ContentRegions"].RequestNavigate(arg);

                    //打开导导航
                    NavigationParameters paras = new NavigationParameters();
                    paras.Add("MsgA", "大家好,我是A");//模块参数传递
                    paras.Add("MsgB", "大家好,我是B");

                    //_regionManager.Regions["ContentRegions"].RequestNavigate(arg, paras);
                    _regionManager.Regions["ContentRegions"].RequestNavigate(arg, callback =>
                    {
                        _navigationJournal = callback.Context.NavigationService.Journal;
                    }, paras);
                });
            }
        }

        /// <summary>
        /// 后退 (记录好上一步后,就可以后退了)
        /// </summary>
        public DelegateCommand<string> BackCommand
        {
            get
            {
                return new DelegateCommand<string>((arg) =>
                {
                    //判断是否可以后退
                    if (_navigationJournal != null && _navigationJournal.CanGoBack)
                    {
                        _navigationJournal.GoBack();//后退
                    }
                });
            }
        }

        /// <summary>
        /// 打开对话框 命令
        /// </summary>
        public DelegateCommand<string> ShowDialogCommand
        {
            get
            {
                return new DelegateCommand<string>((arg) =>
                {
                    //传参数
                    DialogParameters pairs = new DialogParameters();
                    pairs.Add("Title", "动态标题");
                    pairs.Add("Msg", "这是传递的消息");
                    pairs.Add("UserId", 1);//用户ID
                    //页面名称
                    //callback 是回调方法
                    _dialogService.ShowDialog(arg, pairs, callback =>
                    {
                        //接收返回参数
                        if (callback.Result == ButtonResult.OK)
                        {
                            if (callback.Parameters.ContainsKey("Result"))
                            {
                                var result = callback.Parameters.GetValue<string>("Result");
                            }
                            if (callback.Parameters.ContainsKey("Msg"))
                            {
                                var msg = callback.Parameters.GetValue<string>("Msg");
                                MessageBox.Show("获取对话框服务返回消息:" + msg, "系统提示");
                            }
                        }
                    });
                });
            }
        }
    }
}
相关推荐
PfCoder7 分钟前
WinForm真入门(5)——控件的基类Control
c#·visual studio·winform
"孙小浩2 小时前
HarmonyOS应用开发者高级-编程题-001
华为·wpf·harmonyos
yngsqq2 小时前
003集——《利用 C# 与 AutoCAD API 开发 WPF 随机圆生成插件》(侧栏菜单+WPF窗体和控件+MVVM)
wpf
baivfhpwxf202311 小时前
WPF 免费UI 控件HandyControl
ui·wpf
淘源码d12 小时前
如何运用C#.NET快速开发一套掌上医院系统?
开发语言·c#·.net·源码·掌上医院
一个程序员(●—●)12 小时前
xLua环境控制+xLua的Lua调用C#的1
开发语言·unity·c#·lua
qq_3404740213 小时前
6.1 python加载win32或者C#的dll的方法
java·python·c#
Trustport13 小时前
C# EventLog获取Windows日志进行查询设置多个EventLogQuery查询条件
开发语言·c#
勘察加熊人14 小时前
c#的form实现飞机大战
开发语言·c#
观无15 小时前
JWT认证服务
前端·c#·vue