WPF 實現帶蒙版的 MessageBox 消息提示框

来源:https://www.cnblogs.com/yanjinhua/archive/2022/08/09/16565285.html
-Advertisement-
Play Games

WPF 實現帶蒙版的 MessageBox 消息提示框 WPF 實現帶蒙版的 MessageBox 消息提示框 作者:WPFDevelopersOrg 原文鏈接: https://github.com/WPFDevelopersOrg/WPFDevelopers.Minimal 框架使用大於等於.N ...


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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • Python有一個for...else語法,它的寫法如下 for i in range(0,100): if i == 3: break else: print("Not found") 該語句表示:若for迴圈遍歷完畢,則執行else部分的語句。也就是說上述代碼不會有任何輸出,而下述代碼會輸出“N ...
  • 精華筆記: static final常量:應用率高 必須聲明同時初始化 由類名打點來訪問,不能被改變 建議:常量所有字母都大寫,多個單詞用_分隔 編譯器在編譯時會將常量直接替換為具體的數,效率高 何時用:數據永遠不變,並且經常使用 抽象方法: 由abstract修飾 只有方法的定義,沒有具體的實現( ...
  • 一、實現原理 在Servlet3協議規範中,包含在JAR文件/META-INFO/resources/路徑下的資源可以直接訪問。 二、舉例說明 如下圖所示,是我新建的一個Spring Boot Starter項目:zimug-minitor-threadpool,用於實現可配置、可觀測的線程池。其中 ...
  • 1、我們的目標是獲取微博某博主的全部圖片、視頻 2、拿到網址後 我們先觀察 打開F12 隨著下滑我們發現載入出來了一個叫mymblog的東西,展開響應發現需要的東西就在裡面 3、重點來了!!! 通過觀察發現第二頁比第一頁多了參數since_id 而第二頁的since_id參數剛好在上一頁中能獲取到, ...
  • django2 路由控制器 Route路由,是一種映射關係。路由是把客戶端請求的url路徑和用戶請求的應用程式,這裡意指django裡面的視圖進行綁定映射的一種關係。 請求路徑和視圖函數不是一一對應的關係 在django中所有的路由最終都被保存到一個叫urlpatterns的文件里,並且該文件必須在 ...
  • 索引時資料庫提高數據查詢處理性能的一個非常關鍵的技術,索引的使用可以對性能產生上百倍甚至上千倍的影響。接下來,會介紹索引的基本原理、概念,並深入學習資料庫中所使用的索引結構和存儲方式,以及如何管理、維護索引等。 1.索引的基本概念 索引時用來快速查詢表記錄的一種存儲結構,一般使用索引有一下兩個方面: ...
  • 1.避免Scoped模式註冊的服務變成Singleton模式 當提供一個生命周期模式為Singleton的服務實例時,如果發現該服務中還依賴生命周期模式為Scoped的服務實例(Scoped服務實例將被一個Singleton服務實例所引用),那麼這個被依賴的Scoped服務實例最終會成為一個Sing ...
  • 一、JSON(JavaScript Object Notation)的簡介: ① JSON和XML類似,主要用於存儲和傳輸文本信息,但是和XML相比,JSON更小、更快、更易解析、更易編寫與閱讀。 ② C、Python、C++、Java、PHP、Go等編程語言都支持JSON。 二、JSON語法規則: ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...