WPF setting a MenuItem.Icon in code

Viewed 58156

I have an images folder with a png in it. I would like to set a MenuItem's icon to that png. How do I write this in procedural code?

8 Answers
menutItem.Icon = new System.Windows.Controls.Image 
       { 
           Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) 
       };
<MenuItem>
  <MenuItem.Icon>
    <Image>
      <Image.Source>
        <BitmapImage UriSource="/your_assembly;component/your_path_here/Image.png" />
      </Image.Source>
    </Image>
  </MenuItem.Icon>
</MenuItem>

Just make sure your image in also included in the project file and marked as resource, and you are good to go :)

This is how I used it (this way it dont need to be built into the assembly):

MenuItem item = new MenuItem();
string imagePath = "D:\\Images\\Icon.png");
Image icon = new Image();
icon.Source= new BitmapImage(new Uri(imagePath, UriKind.Absolute));
item.Icon = icon;

You can also use your Visual Studio to insert a icon. This is the easiest way

  • Right click at you project in the solution explorer
  • chose Properties
  • Make sure you're in the application page.
  • @ recources you see: Icon and Manifest
  • @ Icon: Click browse and pick your icon.

Problem solved.

Related