UWP消息通知
在Windows 10通常是使用Toast通知方式进行的消息通知,但是在应用通知是不需要通知带有音效的,但是又不能在系统通知中心留下记录,那么需要监听ToastNotification实例的Dismissed事件,利用ToastNotificationManager.History.Remove(toastTag)实现Toast通知在之后消失。
但是在PC上使用是由于通知中心在右下角,对用户可能不是太友好。
所以可以通过Popup+UserControl实现应用内的消息通知。当然实现方法也有很多,用处也不知消息通知,例如:[模态框进度指示器的实现](http://edi.wang/post/2016/2/25/windows-10-uwp-modal-progress-dialog) 。
UWP中实现时就是布置好UserControl的模板,然后延迟一秒之后执行淡出动画。
1 <UserControl.Resources> 2 <Storyboard x:Name="Notification" > 3 <DoubleAnimationUsingKeyFrames Storyboard.TargetName="NotificationGrid" 4 Storyboard.TargetProperty="Opacity" BeginTime="0:0:0"> 5 <SplineDoubleKeyFrame KeyTime="0:0:0.0" Value="1"/> 6 <SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="0.0"/> 7 </DoubleAnimationUsingKeyFrames> 8 </Storyboard> 9 </UserControl.Resources> 10 <Grid Name="NotificationGrid"> 11 <Grid.RowDefinitions> 12 <RowDefinition/> 13 <RowDefinition/> 14 </Grid.RowDefinitions> 15 <Border Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,50" Padding="20,15" Background="Black" > 16 <TextBlock Name="NotificationContent" TextWrapping="Wrap" Foreground="#daffffff"></TextBlock> 17 </Border> 18 </Grid>
然后在cs中加入三个成员变量,分别是存储提示内容,自定延迟时间,还有就是用来显示的Popup类型的成员变量。
myNotification.xaml.cs
1 public sealed partial class myNotification : UserControl 2 { 3 private string content; 4 private TimeSpan showTime; 5 private Popup popup; 6 private myNotification() 7 { 8 this.InitializeComponent(); 9 this.popup = new Popup(); 10 this.Width = Window.Current.Bounds.Width; 11 this.Height = Window.Current.Bounds.Height; 12 popup.Child = this; 13 this.Loaded += Notification_Loaded; 14 this.Unloaded += Notification_Unloaded; 15 } 16 public myNotification(string content,TimeSpan showTime):this() 17 { 18 this.content = content; 19 this.showTime = showTime; 20 } 21 public myNotification(string content):this(content,TimeSpan.FromSeconds(1)) 22 { 23 24 } 25 public void show() 26 { 27 this.popup.IsOpen = true; 28 } 29 private void Notification_Unloaded(object sender, RoutedEventArgs e) 30 { 31 Window.Current.SizeChanged -= Current_SizeChanged; 32 } 33 34 private void Notification_Loaded(object sender, RoutedEventArgs e) 35 { 36 NotificationContent.Text = this.content; 37 this.Notification.BeginTime = this.showTime; 38 this.Notification.Begin(); 39 this.Notification.Completed += Notification_Completed; 40 Window.Current.SizeChanged += Current_SizeChanged; 41 } 42 43 private void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e) 44 { 45 this.Width = e.Size.Width; 46 this.Height = e.Size.Height; 47 } 48 49 private void Notification_Completed(object sender, object e) 50 { 51 this.popup.IsOpen = false; 52 } 53 }
然后在MainPage.xaml中加入一个button,并加入click事件来显示通知。
在click事件中加入:
new myNotification("Hello Wrold").show();
运行效果: