Search code examples
c#wpfnotifyicon

ResourceReferenceKeyNotFoundException on NotifyIcon


I'm using WPF NotifyIcon, and actually I'm trying to learn how to display a simple NotifyIcon in the system tray. Actually In the MainWindow I put this code:

 private TaskbarIcon tb;

 public MainWindow()
 {
      InitializeComponent();       
 }

 private void MetroWindow_StateChanged(object sender, EventArgs e)
 {
      if (WindowState == WindowState.Minimized)
      {
          tb = (TaskbarIcon)FindResource("TestNotifyIcon");
      }
 }

essentially when the main window is minimized the tb should show the Icon declared in a Dictionary like this:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:local="clr-namespace:PrimoCalendarExport.Utils.Resources.UIDictionary"
                xmlns:tb="http://www.hardcodet.net/taskbar">

<tb:TaskbarIcon x:Key="TestNotifyIcon"
              IconSource="/Utils/Images/Test.ico"
              ToolTipText="hello world" />

</ResourceDictionary>

this dictionary of resource is located inside a folder, in particular:

Project name  
   \Utils
       \Resources
          \Dictionary
             \InlineToolTip.xaml

Now the problem's that when I minimize the main window I get this error:

ResourceReferenceKeyNotFoundException

so seems that the TestNotifyIcon can't be located in the project. I don't know what am I doing wrong, I followed all the steps of the tutorial, someone maybe know my mistake? Thanks.


Solution

  • It appears you are looking in the wrong place for the resource. You are looking in the XAML of the metro window however you should be looking in the main window XAML specify to the program where to look using something like this: (I am not currently on visual studio)

     private void MetroWindow_StateChanged(object sender, EventArgs e)
     {
          if (WindowState == WindowState.Minimized)
          {
              tb = (TaskbarIcon)this.FindResource("TestNotifyIcon");
          }
     }
    

    or

     private void MetroWindow_StateChanged(object sender, EventArgs e)
     {
          if (WindowState == WindowState.Minimized)
          {
              tb = (TaskbarIcon)MainWindow.FindResource("TestNotifyIcon");
          }
     }