Thursday 20 July 2017

Toasts 02 Scheduled

Now we are going to create a toast using our ScheduledToastNotification class, firstly we'll use our award winning UI from our previous toast post.

<Page
    x:Class="pc.toastExample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:pc.toastExample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button Click="Button_Click">Send toast</Button>
        </StackPanel>
    </Grid>
</Page>

It really is a minimalist piece...

Let's take a look at our code behind

using System;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace pc.toastExample
{
    public sealed partial class MainPage : Page
    {
        public MainPage() { this.InitializeComponent(); }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var template = ToastTemplateType.ToastText02;
            var xmlDoc = ToastNotificationManager.GetTemplateContent(template);
            var xml = xmlDoc.GetXml();
            /*  <toast>
                    <visual>
                        <binding template="ToastText02">
                            <text id="1"></text>
                            <text id="2"></text>
                        </binding>
                    </visual>
                </toast>*/

            var textElements = xmlDoc.GetElementsByTagName("text");
            textElements[0].AppendChild(xmlDoc.CreateTextNode("Title text"));
            textElements[1].AppendChild(xmlDoc.CreateTextNode("body text"));
           
            var time = DateTimeOffset.Now.AddSeconds(5);
            var toast = new ScheduledToastNotification(xmlDoc, time);
           
            var notifier = ToastNotificationManager.CreateToastNotifier();
            notifier.AddToSchedule(toast);
        }
    }
}


pretty straight forward, there's no events that we can tie into so this really is just a way to notify our user of some piece of information at a specific point in time

now let's say we scheduled some toasts but now we want to remove them. well add another button to our UI and add the following to the click event.

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    var notifier = ToastNotificationManager.CreateToastNotifier();
    var toasts = notifier.GetScheduledToastNotifications();

    foreach (var t in toasts)
        notifier.RemoveFromSchedule(t);

}

simple as that.