Creating Simple Text Notifications in Windows 8 with C#

Windows 8 introduces a much improved notification system that allows your applications to notify users in a variety of ways, from local application notifications to push notifications and badges on live tiles.

The simplest type of notification is a toast notification, which is a message that appears temporarily in the corner of the users screen and then fades away. Various applications have used them for notification of events like users signing on or off, messages received, etc. Windows 8 supports them at the OS level, so you can provide consistent notifications in your applications.

The notification system is in the Windows.UI.Notifications namespace, so the first step is to include the namespace in your code:

using Windows.UI.Notifications;

The notification templates are XML documents, so you also need to include the Windows.Data.Xml.Dom namespace:

using Windows.Data.Xml.Dom;

Creating the notification is simple. First, you use the ToastNotificationManager to get a template to work with for your notification. The GetTemplateContent method returns an XML document containing the template of the type you pass to the method as a ToastTemplateType value. In this case, we just need a simple text template, so we will pass it ToastText01:

XmlDocument x = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);

The Xml document that is returned looks like this:

<toast>
    <visual>
        <binding template="ToastText01">
            <text id="1"></text>
        </binding>  
    </visual>
</toast>

Pulling out the <text> element and appending a text node to it will set the text for the notification:

XmlNodeList toastTextElements = x.GetElementsByTagName("text");
toastTextElements[0].AppendChild(x.CreateTextNode("Copied to clipboard."));

Once the text is set, you create a ToastNotification object and pass the XML template to the constructor:

 ToastNotification toast = new ToastNotification(x);

Finally, you call the CreateToastNotifier method of the ToastNotificationManager and pass the ToastNotification object to the Show method to display it:

  ToastNotificationManager.CreateToastNotifier().Show(toast);

That’s all it takes. There are additional templates you can use that include spaces for images and formatted text. For more information on available templates, see http://msdn.microsoft.com/en-us/library/windows/apps/hh761494.aspx 

Leave a Reply

Your email address will not be published. Required fields are marked *