0

我有一个 WPF VB.NET 应用程序,我想使用嵌入在应用程序资源中的图标作为菜单图标。到目前为止,我有这段代码(在窗口的初始化事件中):

MenuItem.Icon = New Image() With {.Source = New BitmapImage(New
Uri("Resources\Icon.ico", UriKind.Relative))}

而且图标仍然没有显示,有什么想法吗?

4

2 回答 2

1

问题是你的URI。如果在后面的代码中设置它,则必须编写完整的WPF Pack URI。您还必须 将图标文件的构建操作Resource设置为(图标的默认值为None)。

MenuItem.Icon = New Image() With
{
    .Source = New BitmapImage(New Uri("pack://application:,,,/Resources/Icon.ico"))
}

当您在 XAML 中指定 URI 时,默认的 ImageSource TypeConverter 将添加该pack://application:,,,部分,您可以简单地编写

<Image Source="/Resources/Icon.ico"/>
于 2013-02-10T12:43:59.910 回答
0

Better option is building menu in XAML:

  1. Create folder Images in your solution
  2. Add image as Resources to Images directory (in my sample code: "Icon.ico")
  3. In XAML you can use following code:

...

<MenuItem Header="Item1">
    <MenuItem.Icon>
        <Image Source="/Images/Icon.ico" Width="20" Height="20" />
    </MenuItem.Icon>
</MenuItem>

Or if you want to do this in code-behind you can use following code instead of step 3:

MenuItem.Icon = New Image() With {.Source = New BitmapImage(New Uri("/Images/Icon.ico", UriKind.RelativeOrAbsolute))}
于 2013-02-10T12:31:02.347 回答