How to load an icon from file in WPF ?

JerryM 1,131 Reputation points
2021-05-29T17:30:16.777+00:00

Hello,

I have XAML file and a menuitem in it (in a classic menu):

 <MenuItem Name="xml_menuItem_001" Header="_Manage users" />

I would like to load an icon for this menuitem from a file which is placed to:

c:\1\WPF10\media-floppy-5.png

using code-behind. If it possible ?
I am trying this code, but without any success:

            this.xml_menuItem_001.Icon = BitmapFrame.Create(
                                           Application.GetResourceStream(
                                             new Uri(@"c:\1\WPF10\media-floppy-5.png")).Stream);

Is there a suitable way to load the icon from file at running time using code behind ? :)

Jerry

PS: I really like Microsoft, suitable manual is everywhere and it is not necessary for a men to beg for an advice on public forums :) :) :) :) ha ha ha
I am permanently happy ...

Developer technologies Windows Presentation Foundation
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-05-30T09:04:45.833+00:00

    Try something like this:

    this.xml_menuItem_001.Icon = new Image { Source =  new BitmapImage( new Uri( @"c:\1\WPF10\media-floppy-5.png" ) ) };
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Emon Haque 3,176 Reputation points
    2021-05-30T01:50:50.57+00:00

    In one place of my app I've done it this way:

    var image = new Image() {
        Margin = new Thickness(0, 10, 0, 0),
        HorizontalAlignment = HorizontalAlignment.Center,
        VerticalAlignment = VerticalAlignment.Top,
        Width = 96,
        Height = 96,
    };
    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("RentManager.Resources.LoadingIcon.png")){
        image.Source = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
    }
    

    and it works.


  2. JerryM 1,131 Reputation points
    2021-05-31T17:44:19.32+00:00

    wou it is working ok, thanks :)

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.