WPF如何加载生成操作为嵌入资源的图片(不改生成操作)
解决WPF加载Embedded Resources图片的问题
你用的pack://application:,,,/Assets/Images/clock_6.png这种URI只适用于Build Action设为Resource的资源,而你当前把图片设为Embedded Resources,两者的存储机制不同,所以会抛出找不到资源的异常。以下是不用修改生成操作的解决办法:
方法一:后台代码直接加载资源
通过程序集读取嵌入的资源流,转换为BitmapImage后再使用:
using System.Reflection; using System.Windows.Media.Imaging; // 在窗口/控件的构造函数或者初始化方法中执行 var assembly = Assembly.GetExecutingAssembly(); // 资源名称格式:[程序集名称].[文件夹层级].[文件名] // 示例:如果你的程序集叫MyWpfApp,图片路径是Assets/Images/clock_6.png,那么资源名是MyWpfApp.Assets.Images.clock_6.png var resourceName = "MyWpfApp.Assets.Images.clock_6.png"; using (var stream = assembly.GetManifestResourceStream(resourceName)) { if (stream == null) throw new FileNotFoundException("找不到嵌入的资源", resourceName); var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = stream; bitmap.CacheOption = BitmapCacheOption.OnLoad; // 必须设置,否则流关闭后图片无法显示 bitmap.EndInit(); // 将图片加入资源字典,供XAML使用 Resources["clock_6"] = bitmap; }
之后在XAML中就可以正常引用{StaticResource clock_6}了。
方法二:XAML中通过ObjectDataProvider间接加载
先写一个静态工具类封装资源读取逻辑:
using System.Reflection; using System.Windows.Media.Imaging; public static class EmbeddedImageLoader { public static BitmapImage Load(string resourceFullName) { var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream(resourceFullName)) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = stream; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); return bitmap; } } }
然后在XAML资源字典中定义ObjectDataProvider:
<Window xmlns:local="clr-namespace:你的命名空间"> <Window.Resources> <ObjectDataProvider x:Key="clock_6" ObjectType="{x:Type local:EmbeddedImageLoader}" MethodName="Load"> <ObjectDataProvider.MethodParameters> <system:String>MyWpfApp.Assets.Images.clock_6.png</system:String> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> <!-- 使用示例 --> <Image Source="{Binding Source={StaticResource clock_6}}" /> </Window>
注意事项
- 资源名称必须完全匹配:可以通过调用
assembly.GetManifestResourceNames()打印所有嵌入的资源名称,核对你的图片路径是否正确,避免拼写错误或层级错误。 - 确保
CacheOption设为BitmapCacheOption.OnLoad,否则流关闭后图片会无法显示。
内容的提问来源于stack exchange,提问作者Siddharth Mangroliya
相关产品推荐
相关产品推荐

