tags:

views:

143

answers:

1

I am not familiar with WPF, and I just feel quite confusing.

I am trying to create a little computer game, and there are elements I want to display dynamically. I use Image class and add the images to a canvas. But I'm not sure whether it's a good practice. I feel that adding controls to canvas seem to be a little wired. And I'm a little concerned about the performance, because I may need many images.

The real problem is, I can't load the images from the image files. I see an example in a text book like this (XMAL):

<Image Panel.ZIndex="0" Margin="0,0,0,0" Name ="image1">
    <Image.Source>
        <BitmapImage UriSource="Bell.gif" />
    </Image.Source>
</Image>

Where Bell.gif is added into the project.

And I tried to copy this in code to create an image.

new Image { Source = new BitmapImage(new Uri("Blockade.bmp"))}

But I got invalid Uri exception. After some search in the Internet, I found that loading resources dynamically seems to be difficult. Can I load the files added to the project dynamically?

If I use absolute path then it's OK. But I can't expect every computer will put the files in the same location. Can I use relative path?

I tried

new Image { Source = new BitmapImage(new Uri(@"Pictures\Blank Land.bmp", UriKind.Relative)) }

But it doesn't work. (The image is blank)

Thanks.

I deleted the code. I just found the solution in "Pack URIs in WPF" in MSDN. I can either use "pack://application:,,,/Blockade.bmp" (absolute) or "/Blockade.bmp" (Relative) for a resource in the local assembly. (I didn't use '/' at first) "pack://application:,,,/ReferencedAssembly;component/File.xaml" is for referenced assembly. (I guess the problem with the answer is that the authority part is missing)

+2  A: 

The following works:

new BitmapImage(new Uri("/MyProject;component/Resources/next.png", UriKind.Relative));

Just replace "MyProject" with the name of your project, and adjust the path to your image.

Make sure the image is added to the project with the "BuildAction" set to "Resource".

ChrisF
Thank you.Could you explain it a little bit? What does the semicolon mean in the string?
LLS
@LLS - I'm not 100% sure, but I'm pretty sure it's just a delimiter between the project name and the path.
ChrisF
Still, this doesn't work. (But no exception)"BuildAction" is set to "Resource" by default. And I can still only use absolute Uri.
LLS
@LLS - can you update your question with all the code you are using to create the image and put it into your window.
ChrisF