1

i need to create the context menu from code behind in WPF. Everything works great except the Icon, i set the MenuItem icon like this

Dim tsmi As New MenuItem() With {
            .Header = cmd.Name,
            .Icon = cmd.Icon,
            .Tag = cmd
        }

where cmd.Icon is a System.Drawing.Image. What i get instead of the Icon is the string System.Drawing.Image where it should be the Image. Can anyone help?

Stefano Aquila
  • 107
  • 1
  • 10

2 Answers2

1

System.Drawing.Image is from WinForms, what you need is a System.Windows.Controls.Image.

You can make one like this:

New Image() With {.Source = New BitmapImage(New Uri("pack://application:,,,/Your.Assembly.Name;component/Images/image.png"))}

...where you have a file called image.png (marked with Build Action=Resource) in a folder Images in the assembly Your.Assembly.Name.dll.

viking_grll
  • 131
  • 8
  • The first row of your answer was enough to understand what was wrong, unfortunately i don't have the possibility to have the url of my resource. To solve the problem i used this solution: https://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap/6775114 – Stefano Aquila Oct 05 '18 at 07:34
1

The MenuItem documentation shows this XAML:

<MenuItem Header="New">
  <MenuItem.Icon>
    <Image Source="data/cat.png"/>
  </MenuItem.Icon>
</MenuItem>

So you can clearly use a WPF Image control for the icon. The documentation for the Image.Source property provides a link to a topic entitled "How to: Use the Image Element" and it includes this code example:

' Create Image Element 
Dim myImage As New Image()
myImage.Width = 200

' Create source 
Dim myBitmapImage As New BitmapImage()

' BitmapImage.UriSource must be in a BeginInit/EndInit block
myBitmapImage.BeginInit()
myBitmapImage.UriSource = New Uri("C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Water Lilies.jpg")

' To save significant application memory, set the DecodePixelWidth or   
' DecodePixelHeight of the BitmapImage value of the image source to the desired  
' height or width of the rendered image. If you don't do this, the application will  
' cache the image as though it were rendered as its normal size rather then just  
' the size that is displayed. 
' Note: In order to preserve aspect ratio, set DecodePixelWidth 
' or DecodePixelHeight but not both.
myBitmapImage.DecodePixelWidth = 200
myBitmapImage.EndInit()
'set image source
myImage.Source = myBitmapImage

That pretty much gives you everything you need. I have never used any of these types or members before. I just spent some time reading the relevant documentation.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46