Skip to content

Instantly share code, notes, and snippets.

@LGM-AdrianHum
Last active August 6, 2023 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LGM-AdrianHum/60463bec97c4042c2c6b9ba9b61ad782 to your computer and use it in GitHub Desktop.
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.
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);
}
}
@LGM-AdrianHum
Copy link
Author

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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment