Last active
August 6, 2023 22:26
-
-
Save LGM-AdrianHum/60463bec97c4042c2c6b9ba9b61ad782 to your computer and use it in GitHub Desktop.
WPF: Using the pack://application:,,, notation to load a resource and set it as an imagesource in code behind.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void SetImageSourceFromResource() | |
{ | |
try | |
{ | |
// Replace "YourNamespace" with the namespace where the image resource is located | |
Uri imageUri = new Uri("pack://application:,,,/YourNamespace;component/MyImage.png"); | |
// Create a BitmapImage and set it as the source for the Image control | |
BitmapImage bitmapImage = new BitmapImage(imageUri); | |
myImageControl.Source = bitmapImage; | |
} | |
catch (Exception ex) | |
{ | |
MessageBox.Show("Error loading image: " + ex.Message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In the code-behind, we use the SetImageSourceFromResource method to load the image from the resource. The pack://application:,,,/YourNamespace;component/MyImage.png URI format is used to access the image resource from the application's assembly.
Replace "YourNamespace" with the appropriate namespace where your image resource is located. Make sure the Build Action for the image file is set to "Resource" in the Properties window. When the window is loaded, the SetImageSourceFromResource method will be called to load the image and set it as the source for the Image control named "myImageControl".