-
Book Overview & Buying
-
Table Of Contents
Microsoft .NET Framework 4.5 Quickstart Cookbook
By :
Toasts notify the user of relevant and time-sensitive events such as the reception of a new e-mail or a reminder for an approaching appointment.
They will help our application to accomplish another of the Windows Store app principles, which is to feel connected and alive.
We will implement this recipe on the application that we have been developing, but we could apply what we are going to do to any Windows Store app.
Here we are going to add the capability of creating toasts to our app.
Open the application and HelloPage.xaml.cs and add the following using namespaces:
using Windows.Data.Xml.Dom; using Windows.UI.Notifications;
Add there the following method:
private void GenerateToastNotification()
{
ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode("A toast!"));
//The duration
XmlNodeList rootElement = toastXml.GetElementsByTagName("toast");
((XmlElement)rootElement[0]).SetAttribute("duration", "long");
//Create and send the toast
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}Open HelloPage.xaml. Add a button near the header with the text Generate Toast.
On the code behind the click event handler of the added button, add a call to the newly created GenerateToastNotification() method.
Open the Package.appmanifest designer and on the Application UI tab, we will look for the Toast Capable option and select Yes on the combobox.
If we execute the application and click a number of times on the Launch Toast button, our display should look similar to the following image:

In a way very similar to our tile notification, we picked up the toast template type and loaded the template content into an XmlDocument variable.
After this we accessed the element that we wanted to change, in our case the text element, and changed its value.
We changed its duration by setting one of the attributes of the toast element.
Finally, we created ToastNotification from the resulting XML and showed the toast.
We could navigate to a specific destination in our app when the user taps on the toast, as that might be an invitation to explore new and interesting data.
We can use different toast templates, schedule toast notifications, or even send toast push notifications through the WNS.
The toast can be extensively customized with images, sounds, or an expiration time.
Change the font size
Change margin width
Change background colour