设置MenuItem VB的图标

时间:2018-10-04 13:41:11

标签: wpf vb.net imageicon

我需要根据WPF中的代码创建上下文菜单。 除了Icon之外,其他所有功能都很好,我将MenuItem图标设置为

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

其中cmd.Icon是System.Drawing.Image。 我得到的代替Icon的是字符串System.Drawing.Image,它应该是Image。 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

System.Drawing.Image来自WinForms,您需要的是System.Windows.Controls.Image

您可以这样制作:

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

...在程序集image.png中的文件夹Images中,您有一个名为Your.Assembly.Name.dll的文件(标记为Build Action = Resource)。

答案 1 :(得分:1)

MenuItem文档显示了此XAML:

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

因此,您可以为图标使用WPF Image控件。 Image.Source属性的文档提供了一个标题为“如何:使用图像元素”的主题的链接,其中包括以下代码示例:

' 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

几乎可以为您提供所需的一切。我以前从未使用过任何这些类型或成员。我只是花了一些时间阅读相关文档。