WPF实战学习笔记22-添加自定义询问窗口

添加自定义询问窗口

详细代码:https://github.com/DongLiqiang/Mytodo/commit/221de6b2344d5c861f1d3b2fbb2480e3e3b35c26

添加自定义询问窗口显示方法

修改文件Mytodo.Extensions.DialogExtension

添加内容,类中添加内容

c# 复制代码
/// <summary>
/// 显示方法
/// </summary>
/// <param name="name"></param>
/// <param name="parameters"></param>
/// <param name="dialogHostName"></param>
/// <returns></returns>
public static async Task<IDialogResult> Question(this IDialogHostService dialogHost,string Title, string Content, string dialogHostName = "Root")
{
    DialogParameters  param = new DialogParameters();

    //添加参数
    param.Add("Title", Title);
    param.Add("Content", Content);
    param.Add("DialogHostName", dialogHostName);

    //返回对话框实例
    return await dialogHost.ShowDialog("MsgView",param, dialogHostName); 
}

自定义窗体

自定义界面

添加文件Mytodo.Views.MsgView.xaml

复制代码
<UserControl
    x:Class="Mytodo.Views.MsgView"
    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:local="clr-namespace:Mytodo.ViewModels"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    d:DesignHeight="450"
    d:DesignWidth="800"
    mc:Ignorable="d">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>

        <TextBlock
            Padding="5"
            d:Text="温馨提示"
            FontSize="14"
            Text="{Binding Title}" />

        <TextBlock
            Grid.Row="1"
            Padding="15,0"
            VerticalAlignment="Center"
            d:Text="确认删除该数据吗?"
            FontSize="14"
            Text="{Binding Content}" />

        <StackPanel
            Grid.Row="2"
            Margin="10"
            HorizontalAlignment="Right"
            Orientation="Horizontal">
            <Button
                Margin="0,0,10,0"
                Command="{Binding CancelCommand}"
                Content="取消"
                Style="{StaticResource MaterialDesignOutlinedButton}" />
            <Button Command="{Binding SaveCommand}" Content="确定" />
        </StackPanel>
    </Grid>
</UserControl>

添加窗体模型

添加文件:Mytodo.ViewModels.MsgViewModel

c# 复制代码
using MaterialDesignThemes.Wpf;
using Mytodo.Dialog;
using MyToDo.Share.Models;
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 Mytodo.ViewModels
{
    class MsgViewModel
        : BindableBase, IDialogHostAware
        {
            #region 命令定义

                #endregion


                #region 属性定义


                /// <summary>
                /// 对话框内容
                /// </summary>
                public string Content
            {
                get { return content; }
                set { content = value; }
            }


            /// <summary>
            /// 对话框标题 
            /// </summary>
            public string Title
            {
                get { return title; }
                set { title = value; }
            }

            #endregion


                #region 重要字段定义

                #endregion


                #region 字段定义
                private string content;
            private string title;
            #endregion
                public MsgViewModel()
            {
                SaveCommand = new DelegateCommand(Save);
                CancelCommand = new DelegateCommand(Cancel);
            }

            /// <summary>
            /// 取消
            /// </summary>
            private void Cancel()
            {
                if (DialogHost.IsDialogOpen(DialogHostName))
                    DialogHost.Close(DialogHostName, new DialogResult(ButtonResult.No)); //取消返回NO告诉操作结束
            }

            /// <summary>
            /// 确定
            /// </summary>
            private void Save()
            {
                if (DialogHost.IsDialogOpen(DialogHostName))
                {
                    //确定时,把编辑的实体返回并且返回OK
                    DialogParameters param = new DialogParameters();
                    DialogHost.Close(DialogHostName, new DialogResult(ButtonResult.OK, param));
                }
            }

            public string DialogHostName { get; set; }
            public DelegateCommand SaveCommand { get; set; }
            public DelegateCommand CancelCommand { get; set; }

            public void OnDialogOpend(IDialogParameters parameters)
            {
                //获取Title
                if (parameters.ContainsKey("Title"))
                    Title = parameters.GetValue<string>("Title");
                //获取Content
                if (parameters.ContainsKey("Content"))
                    Content = parameters.GetValue<string>("Content");
            }
        }
}

依赖注入

修改:App.xaml.cs

RegisterTypes函数添加

c# 复制代码
containerRegistry.RegisterForNavigation<MsgView, MsgViewModel>();

使用

主界面

修改文件:Mytodo.Views.MainView.cs

修改为

c# 复制代码
using Mytodo.Common.Events;
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;
using Prism.Events;
using Mytodo.Extensions;
using MaterialDesignThemes.Wpf;
using Mytodo.Dialog;
using Prism.Ioc;

namespace Mytodo.Views
{
    /// <summary>
    /// MainView.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : Window
    { 

        private readonly IDialogHostService dialoghost;

        /// <summary>
        /// 订阅消息
        /// </summary>
        public MainView(IEventAggregator aggregator,IContainerProvider provider)
        {
            //检索实例
            dialoghost= provider.Resolve<IDialogHostService>();

            aggregator.Register(arg =>
            {
                DialogHost.IsOpen = arg.IsOpen;

                if (DialogHost.IsOpen)
                    DialogHost.DialogContent = new ProgressView();
            });

            InitializeComponent();

            menuBar.SelectionChanged += (s, e) =>
            {
                drawerHost.IsLeftDrawerOpen = false;
            };

             btnclo.Click += async  (s, e) =>
            {
                //展开确认对话框
                var queres = await DialogExtension.Question(dialoghost, "温馨提示", $"是否要关闭此程序?");
                if (queres.Result != Prism.Services.Dialogs.ButtonResult.OK) return;
                this.Close();
            };

            btnmin.Click += (s, e) =>
            {
                this.WindowState = WindowState.Minimized;
            };

            btnmax.Click += (s, e) =>
            {
                this.WindowState = WindowState.Maximized;
            };

            ColorZone.MouseMove += (s, e) =>
            {
                if (e.LeftButton == MouseButtonState.Pressed)
                    this.DragMove();
            };

            ColorZone.MouseDoubleClick += (s, e) =>
            {
                if (WindowState != WindowState.Normal)
                    WindowState = WindowState.Normal;
                else
                    WindowState = WindowState.Maximized;
            };
        }
    }
}

待办

修改文件Mytodo.ViewModels.TodoViewModel.cs

添加内容

复制代码
private readonly IDialogHostService dialoghost;

修改内容:

c# 复制代码
public TodoViewModel(ITodoService service,IContainerProvider provider) : base(provider)
{
    //检索对话框的实例
    dialoghost = provider.Resolve<DialogHostService>();

    //初始化对象
    TodoDtos = new ObservableCollection<ToDoDto>();  
    RightContentTitle = "添加血雨待办";

    //初始化命令
    SelectedCommand         = new DelegateCommand<ToDoDto>(Selected);
    OpenRightContentCmd     = new DelegateCommand(Add);
    ExecuteCommand          = new DelegateCommand<string>(ExceuteCmd);
    DeleteCommand           = new DelegateCommand<ToDoDto>(DeleteItem);

    this.service = service;
}        
/// <summary>
/// 删除指定项
/// </summary>
/// <param name="dto"></param>
async private void DeleteItem(ToDoDto dto)
{
    //展开确认对话框
    var queres = await DialogExtension.Question(dialoghost, "温馨提示", $"是否要删除此项?{dto.Title}?");
    if (queres.Result != Prism.Services.Dialogs.ButtonResult.OK) return;


    var delres = await service.DeleteAsync(dto.Id);

    if (delres.Status)
    {
        var model = TodoDtos.FirstOrDefault(t => t.Id.Equals(dto.Id));
        TodoDtos.Remove(dto);
    }
}

备忘录

修改文件Mytodo.ViewModels.MemoViewModel.cs

添加内容

c# 复制代码
 private readonly IDialogHostService dialoghost;

修改内容

c# 复制代码
/// <summary>
/// 删除指定项
/// </summary>
/// <param name="dto"></param>
async private void DeleteItem(MemoDto dto)
{
    //展开确认对话框
    var queres = await DialogExtension.Question(dialoghost,"温馨提示",$"是否要删除此项?{dto.Title}?");
    if (queres.Result != Prism.Services.Dialogs.ButtonResult.OK) return;

    var delres = await service.DeleteAsync(dto.Id);

    if (delres.Status)
    {
        var model = MemoDtos.FirstOrDefault(t => t.Id.Equals(dto.Id));
        MemoDtos.Remove(dto);
    }
}
public MemoViewModel(IMemoService service, IContainerProvider provider) : base(provider)
{
    //初始化对象
    MemoDtos = new ObservableCollection<MemoDto>();
    RightContentTitle = "添加备忘率";

    //初始化命令
    SelectedCommand = new DelegateCommand<MemoDto>(Selected);
    OpenRightContentCmd = new DelegateCommand(Add);
    ExecuteCommand = new DelegateCommand<string>(ExceuteCmd);
    DeleteCommand = new DelegateCommand<MemoDto>(DeleteItem);

    //检索DialogHostService类型的实例
    dialoghost = provider.Resolve<DialogHostService>();

    this.service = service;
}
相关推荐
lingggggaaaa1 小时前
小迪安全v2023学习笔记(一百四十五讲)—— Webshell篇&魔改冰蝎&打乱特征指纹&新增加密协议&过后门查杀&过流量识别
笔记·学习·安全·魔改冰蝎·免杀对抗·免杀技术
Digitally2 小时前
如何将iPhone上的笔记传输到电脑
笔记·电脑·iphone
落羽的落羽2 小时前
【C++】现代C++的新特性constexpr,及其在C++14、C++17、C++20中的进化
linux·c++·人工智能·学习·机器学习·c++20·c++40周年
小苏兮2 小时前
【把Linux“聊”明白】编译器gcc/g++与调试器gdb/cgdb:从编译原理到高效调试
java·linux·运维·学习·1024程序员节
im_AMBER2 小时前
React 11 登录页项目框架搭建
前端·学习·react.js·前端框架
lkbhua莱克瓦243 小时前
Java基础——常用算法4
java·数据结构·笔记·算法·github·排序算法·快速排序
学渣676563 小时前
11111
笔记
MeowKnight9583 小时前
【DIY】PCB练习记录2——51单片机核心板
笔记
py有趣9 小时前
LeetCode算法学习之两数之和 II - 输入有序数组
学习·算法·leetcode
BreezeJuvenile10 小时前
外设模块学习(15)——MQ-2烟雾气体传感器(STM32)
stm32·单片机·学习·mq-2·烟雾气体传感器