开发者

How to set the Icon property in code? How to understand the way it is done in XAML?

When I choose an Icon for a wpf Window through the designer I 开发者_StackOverflow社区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#?


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜