Search code examples
wpfnotificationstoast

WPF Toast Notifications


I'm new to WPF, coming from developing WinForms and WebApps, and have much of my application working. I now want to add some Toast style notifications. From what I can gather there is nothing built in to do this and I dont really want to write my own.

I have tried several different NuGet packages but cannot got any to work for one reason or another. The closest I have got is using Nick Stark's ToastNotifications, but when the code goes to create a notification it throws an exception saying it cannot find WarningIcon in resources. I'm surprised its not part of the package, but have added my own icon to resources with the same resource name, but still say issue.

So my question is, does anyone know how to fix this, or able to suggest a package for toast notifications which does just work?

I'm using .net 8.0.

enter image description here


Solution

  • Probably, you forgot to use the included resource dictionary into your App.xaml:

    <Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/ToastNotifications.Messages;component/Themes/Default.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
    </Application.Resources>
    

    Also, make sure you initialize the notifier object properly:

        Notifier _notifier = new Notifier(cfg =>
        {
            cfg.PositionProvider = new WindowPositionProvider(
                parentWindow: Application.Current.MainWindow,
                corner: Corner.TopRight,
                offsetX: 10,
                offsetY: 10);
    
            cfg.LifetimeSupervisor = new TimeAndCountBasedLifetimeSupervisor(
                notificationLifetime: TimeSpan.FromSeconds(3),
                maximumNotificationCount: MaximumNotificationCount.FromCount(5));
    
            cfg.Dispatcher = Application.Current.Dispatcher;
        });
    
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _notifier.ShowWarning("Hello! Warning!", new MessageOptions { ShowCloseButton = true });
        }
    

    This setup works well on Windows 10 + NET 8.0. Please see https://github.com/starkna/ToastNotifications for examples.