WPF 实现带蒙版的 MessageBox 消息提示框

WPF 实现带蒙版的 MessageBox 消息提示框

作者:WPFDevelopersOrg

原文链接: https://github.com/WPFDevelopersOrg/WPFDevelopers.Minimal

  • 框架使用大于等于.NET40
  • Visual Studio 2022;
  • 项目使用 MIT 开源许可协议;
  • Nuget Install-Package WPFDevelopers.Minimal 3.2.6-preview

MessageBox

  • 实现MessageBoxShow五种方法;

    • Show(string messageBoxText) 传入Msg参数;
    • Show(string messageBoxText, string caption) 传入Msg标题参数;
    • Show(string messageBoxText, string caption, MessageBoxButton button) 传入Msg标题操作按钮参数;
    • Show(string messageBoxText, string caption, MessageBoxImage icon) 传入Msg标题消息图片参数;
    • Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon) 传入Msg标题操作按钮消息图片参数;
  • 拿到父级Window窗体的内容Content,放入一个Grid里,再在容器里放入一个半透明的Grid,最后将整个Grid赋给父级Window窗体的内容Content

一、MessageBox.cs 代码如下;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media; namespace WPFDevelopers.Minimal.Controls
{
public static class MessageBox
{
public static MessageBoxResult Show(string messageBoxText)
{
var msg = new WPFMessageBox(messageBoxText);
return GetWindow(msg);
}
public static MessageBoxResult Show(string messageBoxText, string caption)
{
var msg = new WPFMessageBox(messageBoxText, caption);
return GetWindow(msg);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button)
{
var msg = new WPFMessageBox(messageBoxText, caption, button);
return GetWindow(msg);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxImage icon)
{
var msg = new WPFMessageBox(messageBoxText, caption, icon);
return GetWindow(msg);
}
public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
{
var msg = new WPFMessageBox(messageBoxText, caption,button,icon);
return GetWindow(msg);
} static MessageBoxResult GetWindow(WPFMessageBox msg)
{
msg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
Window win = null;
if (Application.Current.Windows.Count > 0)
win = Application.Current.Windows.OfType<Window>().FirstOrDefault(o => o.IsActive);
if (win != null)
{
var layer = new Grid() { Background = new SolidColorBrush(Color.FromArgb(128, 0, 0, 0)) };
UIElement original = win.Content as UIElement;
win.Content = null;
var container = new Grid();
container.Children.Add(original);
container.Children.Add(layer);
win.Content = container;
msg.Owner = win;
msg.ShowDialog();
container.Children.Clear();
win.Content = original;
}
else
msg.Show();
return msg.Result;
}
}
}

二、Styles.MessageBox.xaml 代码如下;

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:wpfsc="clr-namespace:WPFDevelopers.Minimal.Controls"> <ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Themes/Basic/ControlBasic.xaml"/>
<ResourceDictionary Source="../Themes/Basic/Animations.xaml"/>
</ResourceDictionary.MergedDictionaries> <Style TargetType="{x:Type wpfsc:WPFMessageBox}">
<Setter Property="Foreground" Value="{DynamicResource PrimaryTextSolidColorBrush}" />
<Setter Property="Background" Value="{DynamicResource WhiteSolidColorBrush}" />
<Setter Property="BorderBrush" Value="{DynamicResource PrimaryNormalSolidColorBrush}" />
<Setter Property="SizeToContent" Value="WidthAndHeight" />
<Setter Property="ResizeMode" Value="NoResize" />
<Setter Property="ShowInTaskbar" Value="False" />
<Setter Property="SnapsToDevicePixels" Value="True"/>
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="TextOptions.TextFormattingMode" Value="Display" />
<Setter Property="TextOptions.TextRenderingMode" Value="ClearType" />
<Setter Property="WindowStyle" Value="None" />
<Setter Property="FontFamily" Value="{DynamicResource NormalFontFamily}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type wpfsc:WPFMessageBox}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition />
<RowDefinition/>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<DockPanel Margin="20,0,0,0">
<TextBlock x:Name="PART_Title"
HorizontalAlignment="Left"
VerticalAlignment="Center"
FontSize="{DynamicResource TitleFontSize}"
Foreground="{DynamicResource PrimaryTextSolidColorBrush}"/>
<Button Name="PART_CloseButton" Margin="0,6"
ToolTip="Close" HorizontalAlignment="Right"
IsTabStop="False" Style="{DynamicResource WindowButtonStyle}">
<Path Width="10" Height="10"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Data="{DynamicResource PathMetroWindowClose}"
Fill="{DynamicResource PrimaryTextSolidColorBrush}"
Stretch="Fill" />
</Button>
</DockPanel>
</Grid>
<Grid Grid.Row="1" Margin="20">
<DockPanel>
<Path x:Name="PART_Path" Data="{DynamicResource PathInformation}"
Fill="{DynamicResource PrimaryNormalSolidColorBrush}"
Height="25" Width="25" Stretch="Fill"></Path>
<TextBlock x:Name="PART_Message" TextWrapping="Wrap"
MaxWidth="500" Width="Auto" VerticalAlignment="Center"
FontSize="{DynamicResource NormalFontSize}"
Padding="10,0"
Foreground="{DynamicResource RegularTextSolidColorBrush}"/>
</DockPanel>
</Grid>
<Grid Grid.Row="2" Margin="140,20,10,10">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button x:Name="PART_ButtonCancel" Content="取消" Visibility="Collapsed"/>
<Button x:Name="PART_ButtonOK" Style="{DynamicResource PrimaryButton}"
Margin="10,0,0,0" Content="确认"/>
</StackPanel>
</Grid>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style> </ResourceDictionary>

三、WPFMessageBox.cs 代码如下;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes; namespace WPFDevelopers.Minimal.Controls
{
[TemplatePart(Name = TitleTemplateName, Type = typeof(TextBlock))]
[TemplatePart(Name = CloseButtonTemplateName, Type = typeof(Button))]
[TemplatePart(Name = MessageTemplateName, Type = typeof(TextBlock))]
[TemplatePart(Name = ButtonCancelTemplateName, Type = typeof(Button))]
[TemplatePart(Name = ButtonCancelTemplateName, Type = typeof(Button))]
[TemplatePart(Name = PathTemplateName, Type = typeof(Path))]
public sealed class WPFMessageBox : Window
{ private const string TitleTemplateName = "PART_Title";
private const string CloseButtonTemplateName = "PART_CloseButton";
private const string MessageTemplateName = "PART_Message";
private const string ButtonCancelTemplateName = "PART_ButtonCancel";
private const string ButtonOKTemplateName = "PART_ButtonOK";
private const string PathTemplateName = "PART_Path"; private string _messageString;
private string _titleString;
private Geometry _geometry;
private SolidColorBrush _solidColorBrush;
private Visibility _cancelVisibility = Visibility.Collapsed;
private Visibility _okVisibility; private TextBlock _title;
private TextBlock _message;
private Button _closeButton;
private Button _buttonCancel;
private Button _buttonOK;
private Path _path; static WPFMessageBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(WPFMessageBox), new FrameworkPropertyMetadata(typeof(WPFMessageBox)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_title = GetTemplateChild(TitleTemplateName) as TextBlock;
_message = GetTemplateChild(MessageTemplateName) as TextBlock; if (_title == null || _message == null)
throw new InvalidOperationException("the title or message control is null!"); _title.Text = _titleString;
_message.Text = _messageString;
_path = GetTemplateChild(PathTemplateName) as Path;
if (_path != null)
{
_path.Data = _geometry;
_path.Fill = _solidColorBrush;
}
_closeButton = GetTemplateChild(CloseButtonTemplateName) as Button;
if (_closeButton != null)
_closeButton.Click += _closeButton_Click;
_buttonCancel = GetTemplateChild(ButtonCancelTemplateName) as Button;
if (_buttonCancel != null)
{
_buttonCancel.Visibility = _cancelVisibility;
_buttonCancel.Click += _buttonCancel_Click;
}
_buttonOK = GetTemplateChild(ButtonOKTemplateName) as Button;
if (_buttonOK != null)
{
_buttonOK.Visibility = _okVisibility;
_buttonOK.Click += _buttonOK_Click;
}
if (Owner == null)
{
BorderThickness = new Thickness(1);
WindowStartupLocation = WindowStartupLocation.CenterScreen;
}
} private void _buttonOK_Click(object sender, RoutedEventArgs e)
{
Result = MessageBoxResult.OK;
Close();
} private void _buttonCancel_Click(object sender, RoutedEventArgs e)
{
Result = MessageBoxResult.Cancel;
Close();
} private void _closeButton_Click(object sender, RoutedEventArgs e)
{
Close();
} protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
if (Owner == null)
return;
var grid = Owner.Content as Grid;
UIElement original = VisualTreeHelper.GetChild(grid, 0) as UIElement;
grid.Children.Remove(original);
Owner.Content = original;
} public MessageBoxResult Result { get; set; } public WPFMessageBox(string message)
{ _messageString = message;
} public WPFMessageBox(string message, string caption)
{
_titleString = caption;
_messageString = message; } public WPFMessageBox(string message, string caption, MessageBoxButton button)
{
_titleString = caption;
_messageString = message; ;
} public WPFMessageBox(string message, string caption, MessageBoxImage image)
{
_titleString = caption;
_messageString = message;
DisplayImage(image);
} public WPFMessageBox(string message, string caption, MessageBoxButton button, MessageBoxImage image)
{
_titleString = caption;
_messageString = message;
DisplayImage(image);
DisplayButtons(button);
} private void DisplayButtons(MessageBoxButton button)
{
switch (button)
{
case MessageBoxButton.OKCancel:
case MessageBoxButton.YesNo:
_cancelVisibility = Visibility.Visible;
_okVisibility = Visibility.Visible;
break;
//case MessageBoxButton.YesNoCancel:
// break;
default:
_okVisibility = Visibility.Visible;
break;
}
}
private void DisplayImage(MessageBoxImage image)
{
switch (image)
{
case MessageBoxImage.Warning:
_geometry = Application.Current.Resources["PathWarning"] as Geometry;
_solidColorBrush = Application.Current.Resources["WarningSolidColorBrush"] as SolidColorBrush;
break;
case MessageBoxImage.Error:
_geometry = Application.Current.Resources["PathError"] as Geometry;
_solidColorBrush = Application.Current.Resources["DangerSolidColorBrush"] as SolidColorBrush;
break;
case MessageBoxImage.Information:
_geometry = Application.Current.Resources["PathWarning"] as Geometry;
_solidColorBrush = Application.Current.Resources["SuccessSolidColorBrush"] as SolidColorBrush;
break;
case MessageBoxImage.Question:
_geometry = Application.Current.Resources["PathQuestion"] as Geometry;
_solidColorBrush = Application.Current.Resources["PrimaryNormalSolidColorBrush"] as SolidColorBrush;
break;
default:
break;
}
} }
}

Nuget Install-Package WPFDevelopers.Minimal

其他基础控件

1.Window

2.Button

3.CheckBox

4.ComboBox

5.DataGrid

6.DatePicker

7.Expander

8.GroupBox

9.ListBox

10.ListView

11.Menu

12.PasswordBox

13.TextBox

14.RadioButton

15.ToggleButton

16.Slider

17.TreeView

18.TabControl

WPF 实现带蒙版的 MessageBox 消息提示框的更多相关文章

  1. wpf实现仿qq消息提示框

    原文:wpf实现仿qq消息提示框 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/huangli321456/article/details/5052 ...

  2. WPF自定义控件三:消息提示框

    需求:实现全局消息提示框 一:创建全局Message public class Message { private static readonly Style infoStyle = (Style)A ...

  3. MFC上下浮动与渐入渐出消息提示框实现

    类似QQ与360软件,消息提示有两种.上下浮动.渐入渐出. 1.上下浮动提示框实现 机制,定时器响应上下浮动消息. 主要API:MoveWindow. 源码如下UpDownTipDlg.h.UpDow ...

  4. Android消息提示框Toast

    Android消息提示框Toast Toast是Android中一种简易的消息提示框.和Dialog不一样的是,Toast是没有焦点的,toast提示框不能被用户点击,而且Toast显示的时间有限,t ...

  5. easyui 消息提示框

    1.浏览器消息提示框 浏览器弹出框,可以在浏览器设置中被屏蔽掉,导致效果失效 alert() 2.easyui 框架提供的消息框 easyui 框架自带的消息框,不可以被屏蔽. $.messager. ...

  6. UWP中的消息提示框(二)

    在UWP中的消息提示框(一)中介绍了一些常见的需要用户主动去干涉的一些消息提示框,接下来打算聊聊不需要用户主动去干涉的一些消息提示框.效果就是像双击退出的那种提示框. 先说说比较简单的吧,通过系统To ...

  7. 重绘DevExpress的XtraMessageBox消息提示框控件

    先来看提示框,可以看到框其实是一个去掉最大化.最小化按钮后的窗体,窗体的内容就是我们想要提示的内容,重绘提示框其实就是重绘窗体以及中间部分的内容. 首先重绘窗体,消息提示框的窗体不是XtraForm而 ...

  8. 自定义iOS 中推送消息 提示框

    看到标题你可能会觉得奇怪 推送消息提示框不是系统自己弹出来的吗? 为什么还要自己自定义呢? 因为项目需求是这样的:最近需要做 远程推送通知 和一个客服系统 包括店铺客服和官方客服两个模块 如果有新的消 ...

  9. Android第三方开源对话消息提示框:SweetAlertDialog(sweet-alert-dialog)

    Android第三方开源对话消息提示框:SweetAlertDialog(sweet-alert-dialog) Android第三方开源对话消息提示框:SweetAlertDialog(sweet- ...

随机推荐

  1. Pandas复杂查询、数据类型转换、数据排序

    Pandas高级操作 1.复杂查询 (1)逻辑运算 以DataFrame其中一列进行逻辑计算,会产生一个对应的bool值组成的Series 于是我们可以利用返回的bool列表进行一系列的数据查询 (2 ...

  2. 【可视化分析案例】用python分析B站Top100排行榜数据

    一.数据源 之前,我分享过一期爬虫,用python爬取Top100排行榜: 最终数据结果,是这样的: 在此数据基础上,做python可视化分析. 二.数据读取 首先,读取数据源: # 读取csv数据 ...

  3. QQ空间未授权评论_已忽略

    看群友们聊天时发现的, 大概是做了查看了动态访问时间的一个设置, 但是仅自己可见的说说还是被评论了的这么一个问题. 闲的没事就翻了一下找一下问题. 这个方法嘎嘎鸡肋, 可以说完全没用, 交到tsrc, ...

  4. node.js 创建 wss服务

    var https=require('https'); var ws=require('ws'); var fs=require('fs'); var keypath=process.cwd()+'/ ...

  5. BUUCTF-你竟然赶我走

    你竟然赶我走 首先看到这个图片没啥感觉,直接用16进制打开了.拖到最下面果然有flag flag{stego_is_s0_bor1ing}

  6. CAP:多重注意力机制,有趣的细粒度分类方案 | AAAI 2021

    论文提出细粒度分类解决方案CAP,通过上下文感知的注意力机制来帮助模型发现细微的特征变化.除了像素级别的注意力机制,还有区域级别的注意力机制以及局部特征编码方法,与以往的视觉方案很不同,值得一看 来源 ...

  7. easyui combobox重复渲染问题

    当一个页面有两个easyui combobox存在时,并且同时给两个combobox赋相同值,某些easyui的版本会导致其中一个无法切换选项. 解决办法,分两步赋值,可解决问题

  8. ConcurrentHashMap深入剖析(基于JDK1.7)

    最近有点时间,翻了翻ConcurrentHashMap的源码学习了一下,对我自己认为比较重要的一些方法进行了学习,添加了一些必要的注释,拿出来与园子的小伙伴分享一下,有说的不对的地方,还请各位批评指正 ...

  9. [零基础学IoT Pwn] 环境搭建

    [零基础学IoT Pwn] 环境搭建 0x00 前言 这里指的零基础其实是我们在实战中遇到一些基础问题,再相应的去补充学习理论知识,这样起码不会枯燥. 本系列主要是利用网上已知的IoT设备(路由器)漏 ...

  10. 一题多解,ASP.NET Core应用启动初始化的N种方案[下篇]

    [接上篇]"天下大势,分久必合,合久必分",ASP.NET应用通过GenericWebHostService这个承载服务被整合到基于IHostBuilder/IHost的服务承载系 ...