Search code examples
c#xamlwpf-controlsiconsnotifyicon

Embed Icon in WPF application


I am using an icon in my application in two situations.

  1. In XAML as an Image for the Button using DynamicResource.
  2. In C# as NotifyIcon

    this.notifyIcon.Icon = new SystemDrawing.Icon("..//..//Shutdown.ico" );

My problem is if I delete the image the application not working. How can I bind the image with the exe file so that the application can run only with the exe file?


Solution

  • Add the icon to the project as a Resource (not Embedded Resource, there is a difference), then access it with

    using (var stream = Application.GetResourceStream(new Uri("pack://application:,,,/Shutdown.ico")).Stream)
    {
        this.notifyIcon.Icon = new System.Drawing.Icon(stream);
    }
    

    You should also then be able to use it in your XAML too, I just can't remember how yet.

    See here for more information: https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/wpf-application-resource-content-and-data-files

    Note: I have not included any error checking here. You should probably make sure you check the stream to see if it is null before using it.