Set WPF image source using package URI in code
In WPF, when an image is embedded as a resource in a project, the source of the image is usually set in code. However, setting the source using a stream like in the provided code snippet may not display the image.
The solution lies in using package URIs, a special URI type that accesses embedded resources in an assembly.
Create package URI
Package URIs follow a specific format:
<code>pack://application:,,,/**程序集简称**;component/**路径**</code>
Example
In your case the package URI for the image "SomeImage.png" would be:
<code>pack://application:,,,/YourAssemblyName;component/SomeImage.png</code>
Use package URI in code
To set the image source using a package URI, you can use the following code:
<code class="language-c#">Image finalImage = new Image(); ... BitmapImage logo = new BitmapImage(); logo.BeginInit(); logo.UriSource = new Uri("pack://application:,,,/YourAssemblyName;component/SomeImage.png"); logo.EndInit(); ... finalImage.Source = logo;</code>
Alternatively, you can use a shorter constructor:
<code class="language-c#">finalImage.Source = new BitmapImage(new Uri("pack://application:,,,/YourAssemblyName;component/SomeImage.png"));</code>
Key Notes
The above is the detailed content of How to Properly Set WPF Image Sources Using Pack URIs in Code?. For more information, please follow other related articles on the PHP Chinese website!