tags:

views:

6542

answers:

5

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  A: 

menuItem.Icon = new BitmapImage(new Uri("images/sample.png", UriKind.Relative));

Timothy Fries
This helped us tremendously. We had to first create an Image, then assign the source of that Image to the BitMapImage, then set menuItem.Icon = Image object, but it worked.
Scott
As @Scott states, the example code is missing a crucial detail: `menutItem.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) };`
Neil
+5  A: 
<MenuItem>
    <MenuItem.Icon>
        <Image>
            <Image.Source>
                <BitmapImage UriSource="/your_assembly;component/yourpath/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 :)

Arcturus
Original question was for procedural code. Also, I believe in XAML you could write `<Image Source="/CreditAlpha;component/Images/ColorWheel.png" />` inside the `<MenuItem.Icon>`
Neil
A: 

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;
awe
+6  A: 

Arcturus's answer is good because it means you have the image file in your project rather than an independant folder.

So, in code that becomes...

menutItem.Icon = new Image
     {
  Source = new BitmapImage(new Uri("pack://application:,,,/your_assembly;component/yourpath/Image.png"))
     }
IanR
A: 

This is a valid XAML example (requires an extra Image section)

<MenuItem.Icon>
    <Image>
        <Image.Source>
            <BitmapImage UriSource="/your_assembly;component/yourpath/Image.png" />
        </Image.Source>
   </Image>
</MenuItem.Icon>
Entrodus