Stefano Aquila
Stefano Aquila

Reputation: 107

Set icon for MenuItem VB

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?

Upvotes: 1

Views: 283

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

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.

Upvotes: 1

viking_grll
viking_grll

Reputation: 131

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.

Upvotes: 1

Related Questions