从资源加载图像到图像控件

3
我有一个文件夹结构,里面有一些图片。我正在使用C#(而不是XAML)尝试加载并改变这些图片作为代码的背景。然而,我的操作不成功,程序要么抛出异常,要么在应该更改时预加载的图像消失。我已经尝试了从各种问题中提取样本的代码,但仍然没有成功。
文件夹结构:Resources/Images/Themes/{mytheme}.png 生成操作:资源 (所有内容都被添加到resources.resx中)
我目前拥有的代码是...
var themeImage = new BitmapImage();
var filename = string.Format("{0}{1}.png", cmbBaseThemes.SelectedValue.ToString(), cmbAccentColors.SelectedValue.ToString());
themeImage.BeginInit();
themeImage.UriSource = new Uri(@"/ZApp;component/Resources/Images/Themes/" + filename, UriKind.RelativeOrAbsolute);
themeImage.EndInit();
imgThemeStyle.Source = themeImage;

但这段代码总是给我一个异常:"无法定位资源'resources/images/themes/lightindigo.png'。"


All have been added as a resource to resources.resx too” 的意思是什么? - Sinatr
3个回答

0

0

您可能在创建过程中缺少一些参数。

尝试这种方式:

img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.UriSource = new Uri(@"/ZApp;component/Resources/Images/Themes/" + filename, UriKind.RelativeOrAbsolute);
img.EndInit();

我希望我能给这个答案点赞。CreateOptions 是帮助我解决问题的关键。可惜它不是这个问题的答案 ;) - Marcel Grüger

0
在代码后台,您必须使用完全限定的资源文件包Uri
themeImage.UriSource = new Uri(
    "pack://application:,,,/ZApp;component/Resources/Images/Themes/" + filename);

您也可以通过使用带有Uri参数的BitmapImage构造函数来避免BeginInit/EndInit调用:

imgThemeStyle.Source = new BitmapImage(new Uri(
    "pack://application:,,,/ZApp;component/Resources/Images/Themes/" + filename));

无法成功 - “无效的URI:无法解析主机/授权。” - Andy
修改了答案。缺少了双斜杠。 - Clemens

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