WPF Icon and Uri

2020-04-21 03:29发布

问题:

I am trying to load an icon that is in my project directly in the main directory. In order to do that i do this:

Dim uriSrc As Uri = New Uri("pack://ELE100WalkerWPF:,,,/assemblyName;Component/ShowMCF.png")
Dim bitmapImage As BitmapImage = New BitmapImage With {.UriSource = uriSrc}
Dim image As System.Windows.Controls.Image = New System.Windows.Controls.Image() With {.Source = bitmapImage}

This simply doesn't work even if for my styles i reference them in the same way:

<ResourceDictionary Source="pack://application:,,,/ELE100WalkerWPF;component/Resources/Colors.xaml" />

The only difference is that my styles are defined in the MergeDictionary in the application.xaml like this

<ResourceDictionary Source="Resources/Colors.xaml" />

Can somebody please explain why the image is not showing and how i can solve this? Thanks in advance

回答1:

pack://ELE100WalkerWPF:... is not a valid Pack URI.

You can also not set a BitmapImage's UriSource property without calling BeginInit and EndInit. Use the BitmapImage constructor that takes an Uri argument.

Provided that ShowMCF.png is located in the top level folder of your Visual Studio Project, and its Build Action is set to Resource, this should work:

Dim uri As Uri = New Uri("pack://application:,,,/ShowMCF.png")
Dim bitmapImage As BitmapImage = New BitmapImage(uri)

If the image resource is in a referenced assembly (called ELE100WalkerWPF), you must included the assembly name like this:

Dim uri As Uri = New Uri("pack://application:,,,/ELE100WalkerWPF;component/ShowMCF.png")
Dim bitmapImage As BitmapImage = New BitmapImage(uri)