tags:

views:

102

answers:

2

When I choose an Icon for a wpf Window through the designer I get the following XAML:

<Window Icon="/MyNameSpace;component/myIcon.ico">

Please explain this notation for me!

Say I want to set the Icon in the code behind. How do I translate the XAML to C#?

A: 

This is the "pack URI scheme". You can find more about it on MSDN: http://msdn.microsoft.com/en-us/library/aa970069.aspx

In code-behind, you could write the following :

BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri("pack://application:,,,/MyNamespace;component/myIcon.ico");
bitmap.EndInit();
this.Icon = bitmap;

Note that the "MyNamespace" part isn't actually the namespace (since a ressource is not code, it doesn't have a namespace), but the assembly name.

Thomas Levesque
I get an error stating that a string cannot be assigned to the property UriSource
Dabblernl
OK, I fixed the code...
Thomas Levesque
Try as I might I could not get your code to work. It seems that a BitmapImage is not an acceptable ImageSource, the type of the Icon property. But I cannot say I have mastered the several Bitmap and Image concepts of WPF.
Dabblernl
After fixing the URI (see updated code), it works fine for me...
Thomas Levesque
A: 

After much trial and error I found the code below to work, admittedly without comprehending it fully:

var window=new Window();
var uri=new Uri("pack://application:,,,/MyAssembly;component/Icon.ico",
                 UriKind.RelativeOrAbsolute));
// var uri=new Uri("icon.ico",UriKind.Relative) works just as well
window.Icon = BitmapFrame.Create(uri);
Dabblernl