WPF开发随笔收录-仿安卓Toast
一、前言
在项目中,经常需要用到消息提醒功能,在以前接触安卓开发那会使用过Toast,于是打算在WPF上也来模仿一个,话不多说,撸起袖子干起来!
二、正文
1、首先新建一个工程,工程的目录如下
2、编写Toast.cs的代码,这里因为只需要显示文本信息,所以Toast继承Label即可,然后添加一个定时关闭的方法
public class Toast : Label { public Toast() { } public void SetTimeClose(TimeSpan time) { new Thread(() => { Thread.Sleep(time); if (this.Parent is Panel) { this.Dispatcher.BeginInvoke(new Action(() => { (this.Parent as Panel).Children.Remove(this); })); } }) { IsBackground = true }.Start(); } }
3、接着编写一下Toast控件的样式
<Style TargetType="{x:Type ctls:Toast}"> <Setter Property="Foreground" Value="White" /> <Setter Property="FocusVisualStyle" Value="{x:Null}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ctls:Toast}"> <Border MinWidth="50" MinHeight="50" Padding="25,0" Background="#90000000" CornerRadius="2"> <Border.Effect> <DropShadowEffect BlurRadius="10" ShadowDepth="1" /> </Border.Effect> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" TextBlock.FontSize="14" /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style>
4、编辑MainWindow.xaml文件,其中StackPanel是用来添加Toast控件的容器
<Window x:Class="ToastDemo.MainWindow" 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:ToastDemo" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <Grid> <Button Width="100" Height="50" Content="Button" Click="Button_Click"/> </Grid> <StackPanel Name="ToastPanel" Margin="0,80,30,0" HorizontalAlignment="Center" VerticalAlignment="Top" /> </Grid> </Window>
5、接着编写后台代码,添加一个ShowToast方法来生成一个Toast到ToastPanel
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { ShowToast("这是一个Toast"); } public void ShowToast(string text, TimeSpan? time = null) { Toast toast = new Toast(); toast.Content = text; toast.Margin = new Thickness(0, 10, 0, 0); ToastPanel.Children.Add(toast); if (time == null) { toast.SetTimeClose(TimeSpan.FromSeconds(5)); } else { toast.SetTimeClose(time.Value); } } }
6、运行一下看一下效果,可以看到想要的基本效果已经完成了
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构