一、前言
在項目中,經常需要用到消息提醒功能,在以前接觸安卓開發那會使用過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、運行一下看一下效果,可以看到想要的基本效果已經完成了