从代码中加载WPF中的图像
我必须在网上阅读大量的解决方案,但由于一些愚蠢的原因,我无法让他们工作。
我在项目的Resources文件夹中有一个.jpg图像,图像设置为Build Action:Resource(不是嵌入式资源),永远不会复制到输出文件夹。 我的图片未添加到我的resources.resx文件中。
我试图像这样访问该文件:
lResult = new BitmapImage(new Uri(@"pack://application:,,,/Resources/ImageMissing.jpg", UriKind.Absolute));
但这无法说那里没有图像。
这是如此基本我觉得真的很蠢,但我似乎无法掌握资源使用的简单概念。
谢谢。
如果您需要指定从本地程序集引用所引用的资源,那么我认为您希望包含“component”。 例如,我有一些代码从我的代码所在的同一程序集中的资源中加载一个图标。 我写这个:
var SourceUri = new Uri("pack://application:,,,/MyCompany.MyProduct.MyAssembly;component/MyIcon.ico", UriKind.Absolute); thisIcon = new BitmapImage(SourceUri);
如http://msdn.microsoft.com/en-us/library/aa970069.aspx上提供的文章中所述,以下附加示例说明了“组件”的使用:
以下示例显示了位于引用程序集的项目文件夹的根目录中的XAML资源文件的程序包URI。
pack://application:,,,/ReferencedAssembly;component/ResourceFile.xaml
以下示例显示了位于引用程序集的项目文件夹的子文件夹中的XAML资源文件的pack URI。
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
以下示例显示了XAML资源文件的pack URI,该文件位于引用的特定于版本的程序集的项目文件夹的根文件夹中。
pack://application:,,,/ReferencedAssembly;v1.0.0.1;component/ResourceFile.xaml
请注意,引用的程序集资源文件的pack URI语法只能与application:/// authority一起使用。 例如,WPF不支持以下内容。
pack://siteoforigin:,,,/SomeAssembly;component/ResourceFile.xaml
你还需要一个逗号。 以下是WPF中有关Pack URI的文档。 请注意,使用权限时有三个逗号。
lResult = new BitmapImage(new Uri(@"pack://application:,,,/Resources/ImageMissing.jpg", UriKind.Absolute));
您是否碰巧在解决方案资源管理器中重命名文件(或文件夹),然后没有清理或重建应用程序?
如果您肯定您的URI中的名称与解决方案资源管理器中的名称相匹配,请尝试右键单击解决方案并选择“重建”。
问题是图像尚未添加到您的项目中 – 包括它在资源文件中是不够的。
右键单击项目>添加现有项>浏览到并查找并添加图像。
那么你需要做的就是:
myImage = new BitmapImage(new Uri(@"ImageMissing.jpg", UriKind.RelativeOrAbsolute));
您可能将此第二个库创建为“类库”而不是“WPF自定义库”。 在类库中创建xaml文件或将图像作为“资源”嵌入到WPF中是不够的,您可能在AssemblyInfo.cs文件中缺少以下内容:
属性/的AssemblyInfo.cs
[assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
试试这个:
var icon = BitmapFrame.Create(Application.GetResourceStream( new Uri("MyAppBitmap.jpg", UriKind.RelativeOrAbsolute)).Stream);