Loading image from resource into image management
I have a folder structure with some images in which I am trying to load and change the background of my code using C # (not xaml).
I have no luck with this and I either get an exception or the preloaded image becomes invisible when it should change. I've tried code samples from various questions here, but I still have no luck.
Folder structure -> Resources/Images/Themes/{mytheme}.png
Build Action -> Resource (All were added as resource for resources.resx too)
The code I have is there.
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;
But this code always gives me the "Unable to find resource / image / theme / lightindigo.png resources" exception.
source to share
In the code behind you will need to use the fully Resource File Pack Uri
themeImage.UriSource = new Uri(
"pack://application:,,,/ZApp;component/Resources/Images/Themes/" + filename);
You can also avoid calls to BeginInit
/ EndInit
by using a constructor BitmapImage
that takes an argument Uri
:
imgThemeStyle.Source = new BitmapImage(new Uri(
"pack://application:,,,/ZApp;component/Resources/Images/Themes/" + filename));
source to share
Perhaps you are missing some parameters to create.
Try this way:
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();
source to share
Have you tried changing the Uri format? Maybe try a pack of Uri? https://msdn.microsoft.com/en-us/library/vstudio/aa970069(v=vs.100).aspx
source to share