在C#中动态添加和加载资源中的图像

12

我的解决方案中有一些图片,现在它们在解决方案资源管理器中的文件夹images\flowers\rose.png下。我想要一种将这张图片动态加载到我的图片控件上的方法。

我的当前做法是将类型设置为“content”,并使用“copy always”属性。然后像下面这样给出相对路径。

Image2.Source = new BitmapImage(new Uri("/images/flowers/Customswipe_b.png", UriKind.Relative));
有没有办法让程序从资源中加载文件而无需将其复制到目标系统?
3个回答

21

以下对我来说完全没有问题:

image.Source = new BitmapImage(new Uri("pack://application:,,,/YourAssemblyName;component/Resources/someimage.png", UriKind.Absolute));

你还应该将图像的Build ActionNone更改为Resource


8

6

我曾经在查找URI的确切语法时遇到了一些问题,因此请看下面的详细信息:

如果您的图片(myImage.png)位于根目录下的子文件夹“images”中,则确切的语法如下:

image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/myImage.png", UriKind.Absolute));

如果您的图片位于子文件夹images/icon/中(从根目录开始),则语法如下:
image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/icon/myImage.png", UriKind.Absolute));
  • 注意,部分代码"pack://application:,,,不会改变。
  • 请确保将“生成操作”设置为“资源”。

更多信息请参见:此处


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接