Continuing my series based on the presentations I’m giving in Europe, today I turn to toast notifications. As with Tiles, Toast notifications are a great way to let the user know that something interesting is happening with your application.
Toast notifications can be very complex but their essence can be stripped down to just a few lines of code, especially thanks to the NotificationsExtensions library available from Microsoft.
Create a new application, add the NotificationsExtension library and add a reference to the NotificationsExtension library to the main project.
In MainPage.xaml we’lll add a single button to launch the toast,
1: <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
2: <Button Name="xToast"
3: Content="Display Toast"
4: Click="xToast_Click_1" />
5: </Grid>
In the event handler, in the code behind, we’ll begin by declaring a variable that implements the IToastNotificationContent interface.
1: IToastNotificationContent toastContent = null;
We ask the NotificationsExtension library ToastContentFactory to create a ToastText01 Template Content object,
1: IToastText01 templateContent = ToastContentFactory.CreateToastText01();
We set the text property of the Body Text Field of templateContent,
1: templateContent.TextBodyWrap.Text =
2: "This is the body text and if it is too long for the notification, it wraps";
Finallly, we set the IToastNotificationContent object we declared earlier to the templateContent,
1: toastContent = templateContent;
We can now call CreateNotification through the IToastNotificationContent interface, getting back a ToastNotification object,
1: ToastNotification toast = toastContent.CreateNotification();
We call CreateToastNotifier on the library’s ToastNotificationManager to get back a ToastNotifier and we use that to show our toast,
1: ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();
2: notifier.Show(toast);
In its simplest form, that is all it takes to create a toast notification locally. We’ll take a look at using the Windows Notification Service to create toast notifications from the cloud in an upcoming blog post.
Download the project software here
One Response to Windows 8–Toast Notification