我有一个包含一些图像的文件夹结构,我正在尝试使用 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'。”
最佳答案
在后面的代码中,您必须使用完全限定的 Resource File Pack 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));
关于c# - 将图像从资源加载到图像控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31383815/