WPF 制作一个文字漂浮提示框

WPF好像没有自带的文字提示漂浮,我们可以定制一个。

效果如下:

xaml

xaml如下:

csharp 复制代码
<Window x:Class="GroupServer.MsgTip"
        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:GroupServer"
        mc:Ignorable="d"
        Title="MsgTip" ResizeMode="NoResize" Background="#00FFFFFF" AllowsTransparency="True" SizeToContent="WidthAndHeight" Topmost="True" ShowInTaskbar="False" WindowStyle="None" Loaded="Window_Loaded">
    <Border  Background="#91d024" CornerRadius="10" >
        <Label x:Name="labTxt" Margin="20"   HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontSize="18">这是一个消息提示框</Label>
    </Border>
</Window>

这里SizeToContent是适配窗口大小,Topmost是置顶,CornerRadius是圆角。

cs

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;

namespace GroupServer
{
    /// <summary>
    /// MsgTip.xaml 的交互逻辑
    /// </summary>
    public partial class MsgTip : Window
    {
        public MsgTip()
        {
            InitializeComponent();
        }

        public void ShowTxt(string msg, int delaytime = 3000)
        {
            labTxt.Content = msg;
            Show();
            _ = DelayClose(msg, delaytime);
        }

        async Task DelayClose(string msg,int delaytime = 3000)
        {
            await Task.Delay(delaytime);
            Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            MainWindow mainWindow = (MainWindow)Application.Current.MainWindow;
            this.Top = mainWindow.Top + (mainWindow.Height - Height) / 2;
            this.Left = mainWindow.Left + (mainWindow.Width - Width) / 2;
        }
    }
}

WindowLoad是为了让窗口在应用主界面中心显示

我们只要调用ShowTxt函数就可以了。

csharp 复制代码
public static void ShowTip(string msg, int delaytime = 3000)
{
    MsgTip tip = new MsgTip();
    tip.ShowTxt(msg, delaytime);
}
相关推荐
mingupup15 小时前
WPF/C#:使用Microsoft Agent Framework框架创建一个带有审批功能的终端Agent
c#·wpf
△曉風殘月〆19 小时前
WPF中的变换(Transform)功能详解
wpf
mingupup19 小时前
为WPF应用增加项目图标
wpf
张人玉1 天前
c#WPF基础知识
开发语言·c#·wpf
yantuguiguziPGJ1 天前
WPF 联合 Web 开发调试流程梳理(基于 Microsoft.Web.WebView2)
前端·microsoft·wpf
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(二)
.net·wpf·界面控件·devexpress·ui开发·数据网格
大美B端工场-B端系统美颜师2 天前
工控软件开发选择难?Electron、Qt、WPF 对比
qt·electron·wpf
c#上位机2 天前
MefBootstrapper在Prism引导程序中的使用
c#·wpf·prism
没有bug.的程序员3 天前
服务治理与 API 网关:微服务流量管理的艺术
java·分布式·微服务·架构·wpf
Brianna Home3 天前
【案例实战】鸿蒙分布式调度:跨设备协同实战
华为·wpf·harmonyos