In WPF if you are loading images or resources from code, the syntax to do so is less than obvious. Main confusion is with the format that is passed to Uri class constructor and I have gotten it wrong more time than I can count so I thought it would be good thing to write this up so I can refer to it later, and you might find it helpful as well.

The image that is loaded this way is included in the project with Build Action set to Resource (default action). You can verify build action if you right-click the image in your VS.NET Solution Explorer and choose Properties. See what Build Action property is set to, it should be Resource.

So here is code that creates new Image and sets its source, the image in this sample is located in images folder in your project:

Image image = new Image();
image.BeginInit();
image.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/Globe.png",
                                       UriKind.RelativeOrAbsolute));
image.Stretch = Stretch.None;
image.EndInit();

Notice the critical line and syntax for Uri constructor. This will load the image or resource from the same assembly. What to do if you want to load from different assembly? Then use this syntax:

image.Source = new BitmapImage(
          new Uri(@"pack://application:,,,/MyReferencedAssembly/images/Globe.png",
                  UriKind.RelativeOrAbsolute));

Where MyReferencedAssembly is the name of assembly you want to load resource from.

For more information you ever wanted on Pack URI’s check this article in MSDN.

Professional looking applications made easy with DotNetBar for WinForms, Silverlight and WPF User Interface components. Click here to find out more.

Related posts:

  1. Loading XAML ResourceDictionary from code
  2. New in DotNetBar 7.0 part 6, Reflection Image Control
  3. DotNetBar 5.3 Released
  4. When to use NGEN to speedup loading time for .NET Applications
  5. Variable and Fixed calendar sizes for DotNetBar WPF Schedule control