利用WPF的Popup做一种模态弹出对话消息框

在WPF中,Popup是一个可弹出并显示内容的控件,当它显示的时候,始终会显示在UI的最上方,利用这一特性,我们可以扩展它的功能。首先,新建一个用户控件去继承popup控件,前端代码如下:

<Popup x:Class="FilesManager.Dialog.PopupBox"
             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:FilesManager.Dialog"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Border x:Name="border" Background="Gray" CornerRadius="8" MinHeight="35" Width="400" Height="100">
            <TextBlock TextWrapping="WrapWithOverflow"
                       Foreground="White"
                       Margin="10"
                       FontSize="18"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Text="{Binding Path=Message,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:PopupBox}},UpdateSourceTrigger=PropertyChanged}">
            
            </TextBlock>
        </Border>
            
    </Grid>
</Popup>

然后是后端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace FilesManager.Dialog
{
    /// <summary>
    /// PopupBox.xaml 的交互逻辑
    /// </summary>
    public partial class PopupBox : Popup
    {
        public PopupBox()
        {
            InitializeComponent();
            border.MouseUp += (s, e) => { this.IsOpen = false; };
        }



        public new double Opacity
        {
            get { return (double)GetValue(OpacityProperty); }
            set { SetValue(OpacityProperty, value); }
        }

        public static new readonly DependencyProperty OpacityProperty =
            DependencyProperty.Register("Opacity", typeof(double), typeof(PopupBox), new PropertyMetadata(1.0,new PropertyChangedCallback(OnOpacityPropertyChangedCallback)));

        private static void OnOpacityPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (!(d is PopupBox source)) return;
            if (!(e.NewValue is double v)) return;
            source.border.Opacity = v;
        }



        public string Message
        {
            get { return (string)GetValue(MessageProperty); }
            set { SetValue(MessageProperty, value); }
        }

        public static readonly DependencyProperty MessageProperty =
            DependencyProperty.Register("Message", typeof(string), typeof(PopupBox), new PropertyMetadata(string.Empty));

        private static PopupBox dialog = new PopupBox();
        private static DispatcherTimer timer = new DispatcherTimer();

        public static void Show(Window owner,string v,int seconds = 1)
        {
            try
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    dialog.Message = v;
                    dialog.PlacementTarget = owner;
                    dialog.Placement = PlacementMode.Center;
                    dialog.StaysOpen = true;
                    dialog.AllowsTransparency = true;
                    dialog.VerticalOffset = owner.ActualHeight / 3 - 45;
                    dialog.Opacity = 0.9;
                    dialog.IsOpen = true;

                    timer.Tick -= Timer_Tick;
                    timer.Tick += Timer_Tick;
                    timer.Interval = new TimeSpan(0, 0, seconds);
                    timer.Start();
                });
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void Timer_Tick(object sender, EventArgs e)
        {
            timer.Stop();
            Task.Run(() =>
            {
                try
                {
                    for (int i = 0; i < 100; i++)
                    {
                        Thread.Sleep(5);
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            dialog.Opacity -= 0.01;
                        });
                    }

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        dialog.IsOpen = false;
                        dialog.Message = String.Empty;
                    });
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                
            });
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF中,可以使用一个Window控件来实现模态对话,其中包含一个Frame控件来承载Page。 以下是一个简单的示例代码,演示如何使用Window和Frame控件来弹出一个Page模态对话: ```xaml <Window x:Class="ModalPageDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> <Button Content="Open Modal Page" Click="Button_Click"/> </Grid> </Window> ``` ```csharp public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { var modalWindow = new Window { SizeToContent = SizeToContent.WidthAndHeight, WindowStartupLocation = WindowStartupLocation.CenterOwner, Owner = this, Title = "Modal Page" }; var frame = new Frame { Content = new ModalPage() }; modalWindow.Content = frame; modalWindow.ShowDialog(); } } ``` 在这个示例中,我们创建了一个MainWindow窗口,其中包含一个按钮。当用户单击按钮时,我们创建了一个新的Window并将其设置为模态对话。然后,我们在这个Window中添加了一个Frame控件,并将其内容设置为我们想要显示的Page(在这个示例中,我们使用了一个名为ModalPage的自定义Page控件)。 最后,我们使用ShowDialog方法显示这个模态对话,使用户无法与MainWindow进行交互,直到他们关闭了这个模态窗口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值