在UWP應用開發中,咱們經常有向用戶發送一些提示性消息的需求。這種時候咱們通常會選擇MessageDialog、ContentDialog或者ToastNotification來完成功能。html
可是,咱們大多數時候僅僅是須要在應用內向用戶顯示一條提示消息(例如「登陸成功!」),不須要用戶對這條消息作出處理,在這種狀況下這幾種方法都不算是很好的解決方式,它們不夠輕量,也不夠優雅,甚至會阻斷用戶的當前操做,這是咱們所不指望的。java
若是有安卓平臺開發經驗的開發者,可能會想到Toast組件。對,爲何UWP平臺沒有相似Toast的輕量級應用內消息提示組件呢?git
如今,讓咱們來實現一個UWP可用的Toast組件。github
先放一張效果圖:app
在以前《[UWP]使用Popup構建UWP Picker》中咱們講了Picker的實現過程,其中利用到的主要呈現手段就是Popup
。而咱們在這裏想要構建一個代碼中調用的消息通知組件,也能夠採用一樣的方式來實現。async
Toast的主要功能是呈現通知,因此我定義了下面幾個依賴屬性來控制:函數
string
,設置要向用戶呈現的消息內容;TimeSpan
,設置Toast控件在屏幕上的呈現時長。在呈現邏輯上使用一個Popup
做爲加載Toast的容器。這裏的邏輯很是簡單,我直接貼出代碼來,你們一看就能懂。動畫
核心代碼以下:this
public class Toast : Control { // Using a DependencyProperty as the backing store for Content. This enables animation, styling, binding, etc... public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(string), typeof(Toast), new PropertyMetadata(0)); // Using a DependencyProperty as the backing store for Duration. This enables animation, styling, binding, etc... public static readonly DependencyProperty DurationProperty = DependencyProperty.Register("Duration", typeof(TimeSpan), typeof(Toast), new PropertyMetadata(TimeSpan.FromSeconds(2.0))); public Toast(string content) { DefaultStyleKey = typeof(Toast); Content = content; Width = Window.Current.Bounds.Width; Height = Window.Current.Bounds.Height; Transitions = new TransitionCollection { new EntranceThemeTransition() }; Window.Current.SizeChanged += Current_SizeChanged; } public TimeSpan Duration { get => (TimeSpan) GetValue(DurationProperty); set => SetValue(DurationProperty, value); } public string Content { get => (string) GetValue(ContentProperty); set => SetValue(ContentProperty, value); } private void Current_SizeChanged(object sender, WindowSizeChangedEventArgs e) { Width = Window.Current.Bounds.Width; Height = Window.Current.Bounds.Height; } public async void Show() { var popup = new Popup { IsOpen = true, Child = this }; await Task.Delay(Duration); popup.Child = null; popup.IsOpen = false; Window.Current.SizeChanged -= Current_SizeChanged; } }
上面代碼中,我在構造函數裏爲Toast控件添加了一個默認的隱式動畫EntranceThemeTransition
,使它呈現出來的時候不會顯得太生硬。code
Toast控件的默認樣式:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:HHChaosToolkit.UWP.Controls"> <Style TargetType="local:Toast"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="local:Toast"> <Border Margin="0,0,0,60" HorizontalAlignment="Center" VerticalAlignment="Bottom" Background="#af000000" CornerRadius="4"> <TextBlock Margin="30,15" FontSize="14" Foreground="White" Text="{TemplateBinding Content}" /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary>
咱們參考下安卓中Toast的使用方法:
Toast.makeText(getApplicationContext(), "This is a sample toast.",Toast.LENGTH_SHORT).show();
看起來挺長的一句代碼,其實就是經過Toast.makeText()
靜態方法建立了一個新的Toast
,而後調用其show()
方法讓它出如今手機屏幕上。
在這裏,咱們也能夠直接建立一個Toast
,調用其Show()
方法呈現。
或者也能夠建立一個ToastHelper
靜態類來更方便的使用Toast組件:
public static class ToastHelper { public static void SendToast(string content, TimeSpan? duration = null) { var toast = new Toast(content); if (duration.HasValue) { toast.Duration = duration.Value; } toast.Show(); } }
咱們能夠在本身的應用裏爲Toast組件新建一個資源字典,而後將自定義的樣式添加在其中,例如:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="using:HHChaosToolkit.UWP.Controls"> <Style x:Key="CustomToastStyle" TargetType="controls:Toast"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="controls:Toast"> <Border Width="160" Height="160" HorizontalAlignment="Center" VerticalAlignment="Center" Background="#af000000" CornerRadius="4"> <Grid> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <FontIcon FontFamily="Segoe MDL2 Assets" FontSize="50" Foreground="White" Glyph="" /> <TextBlock Grid.Row="1" Margin="30,0,30,15" FontSize="14" Foreground="White" TextWrapping="Wrap" Text="{TemplateBinding Content}" /> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary>
而後在App.xaml中引入咱們編寫好的資源字典。
<Application x:Class="HHChaosToolkit.Sample.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:HHChaosToolkit.Sample" xmlns:viewModels="using:HHChaosToolkit.Sample.ViewModels"> <Application.Resources> <ResourceDictionary> <viewModels:ViewModelLocator x:Name="Locator" /> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Themes/Toast.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
使用時,咱們只須要爲Toast控件設置預約義的樣式便可,或者在咱們上面寫的ToastHelper
類中增長調用自定義樣式Toast的靜態方法:
public static void SendCustomToast(string content, TimeSpan? duration = null) { var toast = new Toast(content); toast.Style = App.Current.Resources["CustomToastStyle"] as Style; if (duration.HasValue) { toast.Duration = duration.Value; } toast.Show(); }
Toast組件是個人開源項目HHChaosToolkit項目中的一部分,其中還有一個與Toast原理差很少的組件WaitingDialog,原理是同樣的,以後不會再單獨寫博文贅述了。
完整的示例代碼在這裏(GitHub),歡迎你們隨意吐槽&提意見!
這篇博文到此結束,謝謝你們閱讀!