views:

48

answers:

1

Hello, I'm working on a Silverlight application and I have a hard time setting the relative path of an image in my application.

This is a brief picture of my project directory:

MyProject L images L mountain1.jpg L SpriteObjects L MountainFactory.cs L GameScreen.xaml

Originally, I painted an Rectangle using an image brush from the GameScreen.xaml.

<Rectangle Name="rec_bg" HorizontalAlignment="Left" VerticalAlignment="Top" Width="800" Height="600">
    <Rectangle.Fill>
        <ImageBrush x:Name="ib_bg" ImageSource="./images/mountain1.jpg" ></ImageBrush>
    </Rectangle.Fill>
</Rectangle>

This xaml code works, that is it can find the image in the images folder without any problem.

I want to change the image dynamically, and I created a class called MountainFactory.cs. In this class, I have a method with this code:

ImageBrush brush = new ImageBrush();
BitmapImage image = new BitmapImage(new Uri("./images/mountain" + level + ".jpg", UriKind.Relative));
brush.ImageSource = image;

This method will return an image brush which is applied to the rec_bg Rectangle object. However, this code cannot find the specified image.

Does anyone who know how to fix this? Thanks.

+1  A: 

It depends on how you are embedded the image. I'm assuming you have it set as "Content" so it's not embedded in the DLL but does embed in the XAP. In that case, you simply access it relative to the project root, so you would be using:

"images/mountain..."

(Note, you don't use the ./ in front of it, you are automatically relative to the root of the application). If you have it set as an embedded resource, you'll need to extract it out of the DLL using a stream - I don't recommend that.

Short story boring: try removing the leading ./ and make sure the properties of the Image have it as Content.

Jeremy Likness