Python Kid
Python Kid

Reputation: 415

Access icon resources through URI VB.NET

I have a WPF VB.NET application and I want to use an icon embedded in the applications resources as a menu icon. So far I have this code (in the window's initialized event):

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

And the icon is still not displayed, any ideas?

Upvotes: 0

Views: 2796

Answers (2)

Clemens
Clemens

Reputation: 128061

The problem is your URI. If you set it in code behind, you must write the full WPF Pack URI. You must also set the Build Action of the icon file to Resource (the default value for icons is None).

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

When you specify the URI in XAML, the default ImageSource TypeConverter will add the pack://application:,,, part, and you could simply write

<Image Source="/Resources/Icon.ico"/>

Upvotes: 1

kmatyaszek
kmatyaszek

Reputation: 19296

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))}

Upvotes: 0

Related Questions