Display toast notifications in a WPF application

Windows 8 has introduced toast notifications. This is very convenient to display an information message when something happens in your application.

Windows Toast Notification

However, this functionality is only available in the UWP api. This API is not available by default in a WPF application. But using a trick you can access it 😃

  1. Edit the csproj to add <TargetPlatformVersion>8.0</TargetPlatformVersion>
<PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetPlatformVersion>8.0</TargetPlatformVersion>
    ...
</PropertyGroup>
  1. Add a reference to Windows

Add reference

Or add the reference in the csproj:

<ItemGroup>
    <Reference Include="System" />
    // ...
    <Reference Include="Windows" />
</ItemGroup>
  1. Create a toast

To create a toast, you must create an xml document that describe the content of the toast. There are predifined templates that you must use. You'll find available template in MSDN: The toast template catalog (Windows Runtime apps)

The following code displays a simple toast with text only:

var message = "Sample message";
var xml = $"<?xml version=\"1.0\"?><toast><visual><binding template=\"ToastText01\"><text id=\"1\">{message}</text></binding></visual></toast>";
var toastXml  = new XmlDocument();
toastXml.LoadXml(xml);
var toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier("Sample toast").Show(toast);

The following code displays a toast with an image and 3 lines of text:

var xml = @"<toast>
    <visual>
        <binding template=""ToastImageAndText04"">
            <image id=""1"" src=""file:///C:\meziantou.jpeg"" alt=""meziantou""/>
            <text id=""1"">Meziantou</text>
            <text id=""2"">Gérald Barré</text>
            <text id=""3"">https://www.meziantou.net</text>
        </binding>
    </visual>
</toast>";
var toastXml  = new XmlDocument();
toastXml.LoadXml(xml);
var toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier("Sample toast").Show(toast);

You can now display toast notifications to your users 😃

Enjoy this blog? Buy Me A Coffee Donate with PayPal

Comments

vmessage8090 -

Ԍreat aгticle, еxactly what I was looking for.

Leave a reply