c# - 将图像从资源加载到图像控件

标签 c# wpf wpf-controls

我有一个包含一些图像的文件夹结构,我正在尝试使用 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/

相关文章:

c# - 在 Windows 运行时从位图创建流

c# - 如何使用U-SQL自定义提取器动态输出多个文件?

c# - Skybound GeckoFX 设置主机字段

c# - 运行 WPF 应用程序的可执行文件时 log4net 不工作

wpf - 我可以在 VS2008 中开发也可以在 Mac 上运行的桌面应用程序吗?什么方法?

c# - 在 ASP.NET MVC 中路由到 Root View

c# - 如何在我的列表框中的每个 ListBoxItem 之间放置一个分隔符?

c# - 如何使 WPF StackPanel 适合网格单元格

c# - 当用户单击任务栏上的程序时检测事件?

c# - WPF + TabControl范围