UWP消息通知

时间:2022-06-18 05:37:53

在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的模板,然后延迟一秒之后执行淡出动画。

     <UserControl.Resources>
<Storyboard x:Name="Notification" >
<DoubleAnimationUsingKeyFrames Storyboard.TargetName="NotificationGrid"
Storyboard.TargetProperty="Opacity" BeginTime="0:0:0">
<SplineDoubleKeyFrame KeyTime="0:0:0.0" Value="1"/>
<SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="0.0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</UserControl.Resources>
<Grid Name="NotificationGrid">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="0,50" Padding="20,15" Background="Black" >
<TextBlock Name="NotificationContent" TextWrapping="Wrap" Foreground="#daffffff"></TextBlock>
</Border>
</Grid>

然后在cs中加入三个成员变量,分别是存储提示内容,自定延迟时间,还有就是用来显示的Popup类型的成员变量。
myNotification.xaml.cs

 public sealed partial class myNotification : UserControl
{
private string content;
private TimeSpan showTime;
private Popup popup;
private myNotification()
{
this.InitializeComponent();
this.popup = new Popup();
this.Width = Window.Current.Bounds.Width;
this.Height = Window.Current.Bounds.Height;
popup.Child = this;
this.Loaded += Notification_Loaded;
this.Unloaded += Notification_Unloaded;
}
public myNotification(string content,TimeSpan showTime):this()
{
this.content = content;
this.showTime = showTime;
}
public myNotification(string content):this(content,TimeSpan.FromSeconds())
{ }
public void show()
{
this.popup.IsOpen = true;
}
private void Notification_Unloaded(object sender, RoutedEventArgs e)
{
Window.Current.SizeChanged -= Current_SizeChanged;
} private void Notification_Loaded(object sender, RoutedEventArgs e)
{
NotificationContent.Text = this.content;
this.Notification.BeginTime = this.showTime;
this.Notification.Begin();
this.Notification.Completed += Notification_Completed;
Window.Current.SizeChanged += Current_SizeChanged;
} private void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
{
this.Width = e.Size.Width;
this.Height = e.Size.Height;
} private void Notification_Completed(object sender, object e)
{
this.popup.IsOpen = false;
}
}

然后在MainPage.xaml中加入一个button,并加入click事件来显示通知。
在click事件中加入:

new myNotification("Hello Wrold").show();

运行效果:UWP消息通知