Setting Window.Icon Property Value From Codebehind
I really got annoyed today by the fact that I could not perform a simple task of setting the Icon property of my WPF window
from codebehind. I tried using the following code:
BitmapImage bmp = newBitmapImage(newUri(@"pack://application:,,/Resources/OptionsDialog.ico"));
this.Icon = bmp;
This kept throwing an exception saying “System.InvalidOperationException: ImageSource for Icon property must be an icon file.”
Well, OptionsDialog.ico is an icon, and I couldn’t find anywhere in the documentation (or in Google) a different way of setting an ImageSource property.
Luckily, it turns out the MSDN WPF forum is a good place to ask questions and it didn’t take long to get an answer (from Ashish Shetty) on how this should be done:
IconBitmapDecoder ibd = new IconBitmapDecoder( new Uri(@"pack://application:,,/Resources/OptionsDialog.ico", UriKind.RelativeOrAbsolute), BitmapCreateOptions.None, BitmapCacheOption.Default);
this.Icon = ibd.Frames[0];
This snippet should be in the Window.Icon property documentation….