How to set window icon in code behind in wpf?
Asked Answered
M

3

19

In xaml it is :

  <View:BaseWindow.Icon>
    /VBDAdvertisement;component/Images/logoVBD.png
  </View:BaseWindow.Icon>

I want to convert it into code behind.

Thanks

Maudiemaudlin answered 24/11, 2011 at 8:50 Comment(1)
Does this answer your question? How to change title bar image in WPF Window?Horlacher
H
27

Something like

myWindow.Icon = new BitmapImage(new Uri("/VBDAdvertisement;component/Images/logoVBD.png"));

You may need to qualify the path more though.

Edit: As i thought the path should be in pack-uri format:

"pack://application:,,,/VBDAdvertisement;component/Images/logoVBD.png"
Hayden answered 24/11, 2011 at 9:16 Comment(2)
yes, it is : myWindow.Icon = new BitmapImage(new Uri("pack://application:,,,/VBDAdvertisement;component/Images/logoVBD.png")); Thanks :)Maudiemaudlin
To avoid the ugly "pack..." strings have a look at #1128147Weese
P
12

This is the correct way to do it (assuming MyIcon.ico is placed on the root folder of a WPF project named MyApplication):

Uri iconUri = new Uri("pack://application:,,,/MyApplication;component/MyIcon.ico");
myWindow.Icon = BitmapFrame.Create(iconUri);

This is also what actually happens when you set the Icon property for the window in XAML.

When just setting the Icon to a new Bitmap, it will not be rendered smoothly and correctly, but instead quite a bit pixelated.

Prioress answered 18/11, 2015 at 8:28 Comment(0)
M
8

Try this its absolutely working for both png as well as ico image format.

window.Icon = BitmapFrame.Create(Application.GetResourceStream(new Uri("LiveJewel.png", UriKind.RelativeOrAbsolute)).Stream);
Moly answered 12/8, 2016 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.