WPF自定义Dialog模板,内容用不同的Page填充

因为审美的不同,就总有些奇奇怪怪的需求,使用框架自带的对话框已经无法满足了,这里记录一下我这边初步设计的对话框。别问为啥要用模板嵌套Page来做对话框,问就是不想写太多的窗体。。。。

模板窗体(XAML)

<Window x:Class="换成自己的程序集.DialogModel"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:SCADA"mc:Ignorable="d"WindowStyle="None"WindowStartupLocation="CenterScreen"AllowsTransparency="True"Background="#060931"Foreground="White"Title="DialogModel" Height="450" Width="600"><Window.Resources><Style TargetType="DockPanel" x:Key="DockPanel"><Setter Property="Background" ><Setter.Value><ImageBrush ImageSource="/Images/top.png"/></Setter.Value></Setter></Style><Style TargetType="StackPanel" x:Key="StackPanel"><Setter Property="Background" ><Setter.Value><ImageBrush ImageSource="/Images/tb_1.png"/></Setter.Value></Setter></Style><Style TargetType="Button" x:Key="Button"><Setter Property="Background" ><Setter.Value><ImageBrush ImageSource="/Images/btn1.png"/></Setter.Value></Setter><Setter Property="BorderThickness" Value="0"/><Setter Property="BorderBrush" Value="Transparent"/><Setter Property="Foreground" Value="White"/></Style></Window.Resources><Grid x:Name="MyDialog"><Grid.RowDefinitions><RowDefinition Height="auto"/><RowDefinition/><RowDefinition Height="auto"/></Grid.RowDefinitions><!--头部--><DockPanel x:Name="TOP" Style="{StaticResource DockPanel}" VerticalAlignment="Center" Height="60" Margin="0"><TextBlock Text="{Binding DialogTitle}" Foreground="White" FontSize="20" VerticalAlignment="Center" Margin="20 0 0 0"/><WrapPanel   VerticalAlignment="Center" HorizontalAlignment="Right"><Button Height="20" Margin="5 0 5 0" Width="20" Padding="0"  Background="Transparent" BorderBrush="Transparent" Foreground="White" x:Name="btnMin" Content="—" /><Button Height="20" Margin="5 0 5 0" Width="20" Padding="0" Background="Transparent" BorderBrush="Transparent" Foreground="White" x:Name="btnMax" Content="❐" /><Button Height="20" Margin="5 0 5 0" Width="20" Padding="0" Background="Transparent" BorderBrush="Transparent" Foreground="White" x:Name="btnClose" Content="╳"/></WrapPanel></DockPanel><!--内容--><Frame x:Name="MainFrame" Content="{Binding CurrentPage}" Grid.Row="1" NavigationUIVisibility="Hidden" BorderThickness="0"/><StackPanel Grid.Row="2" Style="{StaticResource StackPanel}" Visibility="{Binding ISVisible}"><WrapPanel  HorizontalAlignment="Right" ><Button  Style="{StaticResource Button}" Margin=" 0 10 20 10" Click="Confirm" Height="40" Width="120" Content="确定" /><Button  Style="{StaticResource Button}" Margin=" 0 10 10 10" Height="40" Width="120" Click="Cancel"   Content="取消" /></WrapPanel></StackPanel></Grid>
</Window>

模板窗体(cs)

/// <summary>
/// DialogModel.xaml 的交互逻辑
/// </summary>
public partial class DialogModel : Window, INotifyPropertyChanged
{public event PropertyChangedEventHandler PropertyChanged;/// <summary>/// 消息通知方法/// </summary>/// <param name="propertyname"></param>public void OnPropertyChanged([CallerMemberName] string propertyname = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));}public DialogModel(Page page, string title,string Visible= "Visible"){InitializeComponent();DataContext = this;ISVisible = Visible;CurrentPage = page;DialogTitle = title;btnMin.Click += (s, e) => { this.WindowState = WindowState.Minimized; };btnMax.Click += (s, e) =>{if (this.WindowState == WindowState.Maximized)this.WindowState = WindowState.Normal;else{this.ResizeMode = ResizeMode.NoResize;this.WindowState = WindowState.Maximized;}};btnClose.Click += (s, e) => { this.Close(); };TOP.MouseMove += (s, e) =>{if (e.LeftButton == MouseButtonState.Pressed){this.DragMove();}};}#region 字段属性private string title;/// <summary>/// 对话框标题/// </summary>public string DialogTitle{get { return title; }set{title = value; OnPropertyChanged();}}private Page currentpage;public Page CurrentPage{get { return currentpage; }set{currentpage = value; OnPropertyChanged();}}private string visible;/// <summary>/// 是否显示确认取消按钮组,Visible-显示,Collapsed隐藏/// </summary>public string ISVisible{get { return visible; }set{visible = value; OnPropertyChanged();}}#endregion/// <summary>/// 确认方法,此处未返回值是因为主要内容都在Page里面。业务逻辑都在Page中。你也可以放置在此处,具体如何传值得靠你自己/// </summary>private void Confirm(object sender, RoutedEventArgs e){this.DialogResult = true;this.Close();}/// <summary>/// 取消方法/// </summary>private void Cancel(object sender, RoutedEventArgs e){this.Close();}
}

Page(XAML,引用了materialDesign库,没有的话用你自己定义的page就好)

<Page x:Class="*****.Pages.User"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:SCADA.Pages"xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"mc:Ignorable="d" Foreground="White"d:DesignHeight="450" d:DesignWidth="400"Title="User"><Page.Resources><Style TargetType="Grid" x:Key="Grid"><Setter Property="Background"><Setter.Value><ImageBrush ImageSource="/Images/tb_1.png"/></Setter.Value></Setter></Style></Page.Resources><Grid Style="{StaticResource Grid}"><StackPanel Margin="16" Width="300" HorizontalAlignment="Center" VerticalAlignment="Center"><TextBox Margin="10"  Text="{Binding UserName}"materialDesign:HintAssist.Hint="UserName"/><TextBox Margin="10"  Text="{Binding Account}"materialDesign:HintAssist.Hint="Account"/><TextBox Margin="10"  Text="{Binding PassWord}"materialDesign:HintAssist.Hint="PassWord"/><ComboBox x:Name="CurrentRole" SelectionChanged="RoleChange"  Margin="10"  materialDesign:ComboBoxAssist.MaxLength="2" DisplayMemberPath="Name" SelectedValuePath="Id" ItemsSource="{Binding Roles}" materialDesign:HintAssist.Hint="请选择用户角色" materialDesign:HintAssist.HintOpacity=".26" IsEditable="True"></ComboBox><CheckBox Margin="10" Content="是否启用" IsChecked="{Binding IsActive}" /><StackPanel HorizontalAlignment="Right" Orientation="Horizontal"><Button Margin="0,8,8,0" Click="Confirm" Content="确认"></Button><Button Margin="0,8,8,0"  Click="Cancel" Content="取消"></Button></StackPanel></StackPanel></Grid>
</Page>

Page(.cs)

/// <summary>
/// User.xaml 的交互逻辑
/// </summary>
public partial class User : Page, INotifyPropertyChanged
{#region 通知public event PropertyChangedEventHandler PropertyChanged;/// <summary>/// 消息通知方法/// </summary>/// <param name="propertyname"></param>public void OnPropertyChanged([CallerMemberName] string propertyname = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));}#endregion
//这里的数据库用的EF,这里为啥这样写参考我前面的动态配置EF连接字符串的文章,此处可删string SQLConnection = EFConnection.GetConnection(".", "sa", "123456", "XYDB", false);public User(){InitializeComponent();DataContext = this;//必要//下面可删除//Roles = new List<SelectRole>();//Notice.MainUI = Application.Current.MainWindow;//string config = SysConfig.GetConfig(SysConfig.PathBase, "SysSet");//if (config != null)//{//    var mo = JsonConvert.DeserializeObject<SystemSetModel>(config);//    SQLConnection = EFConnection.GetConnection(mo.DbIP, mo.DbAccount, mo.DbPassWord, mo.DbName, false);//}在此初始化所有角色//using (var db = new DBEntities(SQLConnection))//{//    var role = db.SysRoles.Where(m => m.IsActive).ToList();//    if (role != null && role.Count > 0)//    {//        foreach (var item in role)//        {//            SelectRole role1 = new SelectRole();//            role1.Id = item.Id;//            role1.Name = item.RoleName;//            Roles.Add(role1);//        }//    }//}}#region 属性字段private Guid id;/// <summary>/// Id/// </summary>public Guid Id{get { return id; }set{id = value;OnPropertyChanged();//参数可以不写,}}private string username;/// <summary>///用户名/// </summary>public string UserName{get { return username; }set{username = value; OnPropertyChanged();}}private string account;/// <summary>///账号/// </summary>public string Account{get { return account; }set{account = value; OnPropertyChanged();}}private string password;/// <summary>///密码/// </summary>public string PassWord{get { return password; }set{password = value; OnPropertyChanged();}}private bool isactive;/// <summary>/// 状态/// </summary>public bool IsActive{get { return isactive; }set{isactive = value;OnPropertyChanged();}}private bool isadd = true;/// <summary>/// 是否添加用户,用于辨别确认方法是添加还是编辑/// </summary>public bool IsAdd{get { return isadd; }set{isadd = value;OnPropertyChanged();}}private Guid roleid;/// <summary>/// 选定的角色Id/// </summary>public Guid RoleId{get { return roleid; }set{roleid = value;OnPropertyChanged();//参数可以不写,}}private List<SelectRole> roles;/// <summary>/// 可选的角色列表/// </summary>public List<SelectRole> Roles{get { return roles; }set{roles = value;OnPropertyChanged();}}#endregion/// <summary>/// 添加/编辑/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Confirm(object sender, RoutedEventArgs e){try{//下面的逻辑替换成自己的//using (var db = new DBEntities(SQLConnection))//{//    //添加用户//    if (IsAdd)//    {//        var Current = db.SysUsers.FirstOrDefault(m => m.Account == Account);//        if (Current == null)//        {//            SysUser user = new SysUser();//            user.Id = Guid.NewGuid();//            user.Name = UserName;//            user.Account = Account;//            user.PassWord = PassWord;//            user.IsActive = IsActive;//            user.CreateTime = DateTime.Now;//            user.LoginNum = 0;//            user.LoginTime = DateTime.Now;//            User_Role user_Role = new User_Role();//            user_Role.Id = Guid.NewGuid();//            user_Role.UserId = user.Id;//            user_Role.RoleId = RoleId;//            user.User_Role.Add(user_Role);//            db.SysUsers.Add(user);//            db.SaveChanges();//            Notice.SuccessNotification_Dark("添加成功", 20, 5);//            // 获取当前页面所在的窗体//            Window window = Window.GetWindow(this);//            // 检查是否找到窗体并关闭它//            if (window != null)//            {//                window.Close();//            }//        }//        else//        {//            Notice.WarningNotification_Dark($"当前用户账号已存在!", 20, 5);//        }//    }//编辑用户//    else//    {//        var Current = db.SysUsers.FirstOrDefault(m => m.Id != Id && m.Account == Account);//        if (Current == null)//        {//            var User = db.SysUsers.FirstOrDefault(m => m.Id == Id);//            if (User != null)//            {//                db.Entry(User).State = EntityState.Detached;//取消跟踪免得修改主键冲突//                User.Name = UserName;//                User.Account = Account;//                User.PassWord = PassWord;//                User.IsActive = IsActive;//                var role = User.User_Role.FirstOrDefault();//                if (role != null)//有配置角色//                {//                    role.RoleId = RoleId;//                    db.User_Role.Add(role);//                }//                else//无配置角色//                {//                    User_Role userRole = new User_Role();//                    userRole.Id = Guid.NewGuid();//                    userRole.UserId = User.Id;//                    userRole.RoleId = RoleId;//                    db.User_Role.Add(userRole);//                }//                db.Entry(User).State = EntityState.Modified;//                db.SaveChanges();//                Notice.SuccessNotification_Dark("编辑成功", 20, 5);//                // 获取当前页面所在的窗体//                Window window = Window.GetWindow(this);//                // 检查是否找到窗体并关闭它//                if (window != null)//                {//                    window.Close();//                }//            }//            else//            {//                Notice.FailtureNotification_Dark("未找到当前用户", 20, 5);//                return;//            }//        }//        else//        {//            Notice.WarningNotification_Dark($"当前账号已存在!", 20, 5);//        }//    }//}}catch (Exception ex){Notice.FailtureNotification_Dark($"失败:{ex.Message}", 20, 5);}}/// <summary>/// 取消/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Cancel(object sender, RoutedEventArgs e){// 获取当前页面所在的窗体Window window = Window.GetWindow(this);// 检查是否找到窗体并关闭它if (window != null){window.Close();}}private void RoleChange(object sender, SelectionChangedEventArgs e){RoleId=(Guid)CurrentRole.SelectedValue;}
}
public class SelectRole
{public Guid Id { get; set; }public string Name { set; get; }
}

使用方法(供参考):

添加用户:

User user = new User();
DialogModel dialog = new DialogModel(user, "添加用户", "Collapsed");
dialog.ShowDialog();

编辑用户(需要赋值):

 /// <summary>/// DataGird的自定义操作栏的编辑按钮/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void UserEdit(object sender, RoutedEventArgs e){UserInfoDto userInfo = new UserInfoDto();var co = (Control)sender;userInfo = (UserInfoDto)co.DataContext;//获取当前行数据User user = new User();//实例化Pageuser.IsAdd = false;//标识是编辑user.Id = userInfo.Id;//将当前行信息给到Page,绑定到控件user.UserName = userInfo.Name;user.Account = userInfo.Account;user.PassWord = userInfo.PassWord;user.IsActive = userInfo.IsActive;user.RoleId = userInfo.RoleId;for (int i = 0; i < user.Roles.Count; i++){if (user.Roles[i].Id == userInfo.RoleId){if (user.Roles.Count > 1){user.Roles.Remove(user.Roles[i]);user.Roles.Insert(0, user.Roles[i]);}}}DialogModel dialog = new DialogModel(user, "编辑用户", "Collapsed");dialog.ShowDialog();}

最终结果(用到的背景图片啥的我就不贴了,毕竟我觉得不太好看):

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/430530.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

独立游戏《Project:Survival》UE5C++开发日志0——游戏介绍

该游戏是《星尘异变》团队的下一款作品&#xff0c;太空科幻题材的生存游戏&#xff0c;我将负责使用C、蓝图实现游戏的基础框架和核心功能&#xff0c;其中还包含使用人工智能算法助力游戏开发或帮助玩家运营 目前已有功能&#xff1a; 1.3D库存系统&#xff1a;所有库存中的物…

1.6 计算机网络体系结构

参考&#xff1a;&#x1f4d5;深入浅出计算机网络 常见的三种计算机网络体系结构 TCP/IP体系结构 路由器一般只包含网络接口层和网际层。 应用层TCP/IP体系结构的应用层包含了大量的应用层协议&#xff0c;例如HTTP、SMTP、DNS、RTP等运输层TCP和UDP是TCP/IP体系结构运输层的…

UWA支持鸿蒙HarmonyOS NEXT

华为在开发者大会上&#xff0c;宣布了鸿蒙HarmonyOS NEXT将仅支持鸿蒙内核和鸿蒙系统的应用&#xff0c;不再兼容安卓应用&#xff0c;这意味着它将构建一个全新且完全独立的生态系统。 为此&#xff0c;UWA也将在最新版的UWA SDK v2.5.0中支持鸿蒙HarmonyOS NEXT&#xff0c…

链表分割-----------lg

现有一链表的头指针 ListNode* pHead&#xff0c;给一定值x&#xff0c;编写一段代码将所有小于x的结点排在其余结点之前&#xff0c;且不能改变原来的数据顺序&#xff0c;返回重新排列后的链表的头指针。 我们可以假设x为36&#xff0c;则小于36都排在前边&#xff0c;>3…

虚幻引擎游戏保存/加载存档功能

函数名功能Does Save Game Exist检查存档是否存在Load Game from Slot加载存档Save Game to Slot保存存档Delete Game in Slot删除存档 Slot Name 是插槽名字 存档都是通过插槽名字来 读取/加载/检查/删除的 先创建一个SaveGame类 , 这个类里可以存放要保存的数据 , 比如 玩家…

【UE5】将2D切片图渲染为体积纹理,最终实现使用RT实时绘制体积纹理【第二篇-着色器制作】

在上一篇文章中&#xff0c;我们已经理顺了实现流程。 接下来&#xff0c;我们将在UE5中&#xff0c;从头开始一步一步地构建一次流程。 通过这种方法&#xff0c;我们可以借助一个熟悉的开发环境&#xff0c;使那些对着色器不太熟悉的朋友们更好地理解着色器的工作原理。 这篇…

思科安全网络解决方案

《网安面试指南》http://mp.weixin.qq.com/s?__bizMzkwNjY1Mzc0Nw&mid2247484339&idx1&sn356300f169de74e7a778b04bfbbbd0ab&chksmc0e47aeff793f3f9a5f7abcfa57695e8944e52bca2de2c7a3eb1aecb3c1e6b9cb6abe509d51f&scene21#wechat_redirect 《Java代码审…

Redis数据持久化总结笔记

Redis 是内存数据库&#xff0c;如果不将内存中的数据库状态保存到磁盘&#xff0c;那么一旦服务器进程退出&#xff0c;服务器中的数据库状态也会消失。所以 Redis 提供了持久化功能&#xff01; Redis 提供了 2 个不同形式的持久化方式 RDB&#xff08;Redis DataBase&#…

【python】requests 库 源码解读、参数解读

文章目录 一、基础知识二、Requests库详解2.1 requests 库源码简要解读2.2 参数解读2.3 处理响应2.4 错误处理 一、基础知识 以前写过2篇文章&#xff1a; 计算机网络基础&#xff1a; 【socket】从计算机网络基础到socket编程——Windows && Linux C语言 Python实现…

排序----希尔排序

void ShellSort(int* a, int n) {int gap n;while (gap > 1){// 1保证最后一个gap一定是1// gap > 1时是预排序// gap 1时是插入排序gap gap / 3 1;for (size_t i 0; i < n - gap; i){int end i;int tmp a[end gap];while (end > 0){if (tmp < a[end]){…

英伟达NVIDIA数字IC后端笔试真题(ASIC Physical Design Engineer)

今天小编给大家分享下英伟达NVIDIA近两年数字IC后端笔试真题&#xff08;ASIC Physical Design&#xff09; 请使用OR门和INV反相器来搭建下面所示F逻辑表达式的电路图。 数字IC后端设计如何从零基础快速入门&#xff1f;(内附数字IC后端学习视频&#xff09; 2024届IC秋招兆…

WEB领域是不是黄了还是没黄

进入2024年后&#xff0c;WEB领域大批老表失业&#xff0c;一片哀嚎&#xff0c;个个饿的鬼叫狼嚎&#xff0c;为啥呢&#xff0c;下面是我个人的见解和看法。 中国程序员在应用层的集中 市场需求&#xff1a;中国的互联网行业在过去几年中经历了爆炸性增长&#xff0c;尤其是…

RAG技术全面解析:Langchain4j如何实现智能问答的跨越式进化?

LLM 的知识仅限于其训练数据。如希望使 LLM 了解特定领域的知识或专有数据&#xff0c;可&#xff1a; 使用本节介绍的 RAG使用你的数据对 LLM 进行微调结合使用 RAG 和微调 1 啥是 RAG&#xff1f; RAG 是一种在将提示词发送给 LLM 之前&#xff0c;从你的数据中找到并注入…

Linux-DHCP服务器搭建

环境 服务端&#xff1a;192.168.85.136 客户端&#xff1a;192.168.85.138 1. DHCP工作原理 DHCP动态分配IP地址。 2. DHCP服务器安装 2.1前提准备 # systemctl disable --now firewalld // 关闭firewalld自启动 # setenforce 0 # vim /etc/selinux/config SELINU…

828华为云征文|华为云Flexus云服务器X实例 基于CentOS系统镜像快速部署Laravel开源论坛

最近公司可热闹了&#xff01;大家都在为搭建博客论坛系统忙得不可开交&#xff0c;尤其是在选服务器这件事儿上&#xff0c;那叫一个纠结。 同事 A 说&#xff1a;“咱得选个厉害的服务器&#xff0c;不然这论坛以后卡得跟蜗牛爬似的可咋办&#xff1f;” 同事 B 回应道&#…

【AcWing】【C++】模板之区间和与区间合并

最近在对程序设计算法进行复习&#xff0c;终于复习完了AcWing基础算法课的第一章&#xff0c;在此对第一章最后两个模板区间和与区间合并进行记录与分享。 区间和 题目描述与输入输出样例 题目来自于AcWing 802. 区间和。 思路 从题目描述来说&#xff0c;第一眼看来这是…

Fyne ( go跨平台GUI )中文文档-入门(一)

本文档注意参考官网(developer.fyne.io/) 编写, 只保留基本用法go代码展示为Go 1.16 及更高版本, ide为goland2021.2 这是一个系列文章&#xff1a; Fyne ( go跨平台GUI )中文文档-入门(一)-CSDN博客 Fyne ( go跨平台GUI )中文文档-Fyne总览(二)-CSDN博客 Fyne ( go跨平台GUI )…

镭射限高防外破预警装置-线路防外破可视化监控,安全尽在掌握中

镭射限高防外破预警装置-线路防外破可视化监控&#xff0c;安全尽在掌握中 在城市化浪潮的汹涌推进中&#xff0c;电力如同现代社会的生命之脉&#xff0c;其安全稳定运行直接关系到每一个人的生活质量和社会的整体发展。然而&#xff0c;随着建设的加速&#xff0c;电力设施通…

部署wordpress项目

一、先部署mariadb 二、在远程登录工具上进行登录测试&#xff0c;端口号为30117&#xff0c;用户为 root&#xff0c;密码为123 三、使用测试工具&#xff1a; [rootk8s-master aaa]# kubectl exec -it pods/cluster-test0-58689d5d5d-7c49r -- bash 四、部署wordpress [root…

论文阅读 | 基于流模型和可逆噪声层的鲁棒水印框架(AAAI 2023)

Flow-based Robust Watermarking with Invertible Noise Layer for Black-box DistortionsAAAI, 2023&#xff0c;新加坡国立大学&中国科学技术大学本论文提出一种基于流的鲁棒数字水印框架&#xff0c;该框架采用了可逆噪声层来抵御黑盒失真。 一、问题 基于深度神经网络…