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.Source = new BitmapImage(new Uri(@"pack://application:,,,/images/Globe.png",
image.Stretch = Stretch.None;

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

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.

Tagged with:

I’ve often had a need to check whether DependencyProperty holds its default value and surprisingly it is not as easy to find how to do that. So I present IsDefaultValue method:

public bool IsDefaultValue(DependencyObject targetObject, DependencyProperty dp)
    return System.Windows.DependencyPropertyHelper.GetValueSource(targetObject, _
       dp).BaseValueSource == BaseValueSource.Default;

And that’s it!

As bonus, if you look into the BaseValueSource enum you might find other interesting things 😉

Tagged with:

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

© 2009 Denis Basaric: DevComponents Blog