Tips and tricks for C# and JavaScript Windows 8 developers: Using notifications for non-modal messages

When you want to display a message to inform your user, it is not always a good idea to use a modal MessageDialog which can be really annoying for the user.

A better way can be to use a notification in order to display a non-intrusive dialog for the user:

To do so here is the code with C#:

public static void ShowNotification(string title, string message)
{
    const ToastTemplateType template = Windows.UI.Notifications.ToastTemplateType.ToastText02;
    var toastXml = Windows.UI.Notifications.ToastNotificationManager.GetTemplateContent(template);

    var toastTextElements = toastXml.GetElementsByTagName("text");
    toastTextElements[0].AppendChild(toastXml.CreateTextNode(title));
    toastTextElements[1].AppendChild(toastXml.CreateTextNode(message));

    var toast = new Windows.UI.Notifications.ToastNotification(toastXml);

    var toastNotifier = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();
    toastNotifier.Show(toast);
}

And the JavaScript version:

var showNotification = function (title, message) {
    var notifications = Windows.UI.Notifications;

    var template = notifications.ToastTemplateType.toastText02;
    var toastXml = notifications.ToastNotificationManager.getTemplateContent(template);

    var toastTextElements = toastXml.getElementsByTagName("text");
    toastTextElements[0].appendChild(toastXml.createTextNode(title));
    toastTextElements[1].appendChild(toastXml.createTextNode(message));

    var toast = new notifications.ToastNotification(toastXml);

    var toastNotifier = notifications.ToastNotificationManager.createToastNotifier();
    toastNotifier.show(toast);
};

And obviously do not forget to activate the toast capable feature in the Package.appxmanifest file: