Display toast notifications in a WPF application

 
 
  • GĂ©rald BarrĂ©
 

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

Windows Toast NotificationWindows 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>

    csproj (MSBuild project file)
    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetPlatformVersion>8.0</TargetPlatformVersion>
        ...
    </PropertyGroup>
  2. Add a reference to Windows

    Add referenceAdd reference

    Or add the reference in the csproj:

    csproj (MSBuild project file)
    <ItemGroup>
        <Reference Include="System" />
        // ...
        <Reference Include="Windows" />
    </ItemGroup>
  3. Create a toast

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

The following code displays a simple toast with text only:

C#
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:

C#
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 😃

Do you have a question or a suggestion about this post? Contact me!

Follow me: