views:

133

answers:

2

I have something like this in my xaml:

<Grid>
    <Image Name="image" Source="../../Images/DefaultImage.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Image>
</Grid>

How can I get (using my code-behind c# code) the absolute path of the image source?

A: 

You could try this:

string path = ((BitmapImage)image.Source).UriSource.AbsolutePath;
Robin
It doesn't work. I get an exception because of the cast to BitmapImage
melculetz
Is it acceptable for you to force a bitmap image? As in:<Image ...> <Image.Source> <BitmapImage UriSource="../../Images/DefaultImage.png" /> </Image.Source></Image>
Robin
Yes, if I would have the image declared this way, it should work, but I have it differently
melculetz
+1  A: 

When converted from a Uri string or filename, the ImageConverter creates a BitmapDecoder and extracts its first Frame. Getting the Uri should be possible with:

((BitmapFrame)image.Source).Decoder.ToString()

Note that this will generally return an absolute Uri rather than the original Uri found in the XAML. If you need the exact original Uri from the XAML, it is found in the _uri field of the BitmapDecoder but you'll need reflection and elevated code permissions to get to it, plus your code may not work in future NET Framework versions.

Ray Burns