tags:

views:

18

answers:

2

Hi,

I have an Image declared in some XAML as:

<Image Width="188" Height="56" HorizontalAlignment="Left"  VerticalAlignment="Bottom" Margin="10,0,0,10" Grid.ColumnSpan="2" Grid.Column="0" Source="..\Images\myImage.png" />

This is a static image and does not need to change during program execution.

I also have an image which does need to change at runtime, depending on a set of values.

I am using an iValueConverter to convert the data to images, which seems to work, but I am having trouble creating the images themselves.

I am attempting to create a series of System.Windows.Media.Imaging.BitmapImage objects to store the images. As in the code above, I am trying to access a .PNG stored in the \Images directory:

Dim ThisImage As New BitmapImage(New Uri("..\Images\thisImage.png", UriKind.Relative))

Whereas using `"..\Images\" appears to work fine for the XAML, correctly opening the image stored in [Project Directory]\Images\, in code it seems to direct to [Project Directory]\bin\Images\, which doesn't exist.

I'm obviously screwing up something, here, but I don't want to start trying to navigate directly to the file, as it obviously won't be in the same location once it's installed...

What am I missing, here? Why is the XAML URI not working the same as the code URI?

+1  A: 

Well, the issue is that you're using a relative Uri when, in this context, you'll have to provide an absolute one.

It works as you are expecting in XAML because, within the ImageSourceConverter (which is used to convert a Uri in xaml into an ImageSource), relative Uris are converted to absolute Uris by using the IUriContext service which is available via the ITypeDescriptorContext. In other words, the Uri isn't magic. There is lots of heavy work being done (in this case, by the xaml deserializer) in order to transform a relative Uri in xaml into an ImageSource.

Will
+1  A: 

When you define the Image.Source property in XAML with a URI, a converter (ImageSourceConverter) is used to convert that URI to an ImageSource instance. The converter has access to the IUriContext of the XAML element, so it knows the base URI to use to resolve the relative URI.

When you create a BitmapImage in code, the BitmapImage class doesn't have access to the URI context, so it doesn't know how to resolve the relative URI. You need to specify an absolute URI, with the form "pack://application:,,,/Images/thisImage.png"

Thomas Levesque
Thanks. I've has a nice read-through of the [Pack URIs in WPF](http://msdn.microsoft.com/en-us/library/aa970069.aspx) page. Most useful.
Frosty840