by WindowsPhoneGeek
Generally there are two ways to include an image(other resource) in a Windows Phone 7 project : as build action "Content" or build action "Resource". In this tutorial I will give some examples of how to reference images depending on their build action and will share some performance tips as well.
To begin with lets first say that in this demo I will use thefollowingstructure of the images:
Performance Consideration
For a better performance we would suggest that you compile your images with a "Build Action" of "Content" instead of the default "Resource". When adding new images to your project by default the "Build Action" is set to "Resource" (under the Properties window). Make sure to always change this to "Content" in order to reduce the size of your DLL, speeding up both app load and image load.
Content
If you set the build action to "Content" the image is included in the XAP alongside the DLL.
When you use "Build Action" of type "Content" then you access your image in this way:
XAML:
1
|
<
Image
Stretch
=
"None"
Source
=
"/images/appbar.cancel.rest.png"
/>
|
C#:
1
2
3
4
|
//Content
Uri uri =
new
Uri(
"/images/appbar.cancel.rest.png"
, UriKind.Relative);
BitmapImage imgSource =
new
BitmapImage(uri);
this
.image.Source = imgSource;
|
Resource
All resources are embedded in your assembly (DLL).
When you use "Build Action" of type "Resource" then you access your image in this way:
XAML:
1
|
<
Image
Source
=
"/WP7SampleProject3;component/images/appbar.feature.email.rest.png"
/>
|
C#:
1
2
3
4
|
//Resource
Uri uriR =
new
Uri(
"/WP7SampleProject3;component/images/appbar.feature.email.rest.png"
, UriKind.Relative);
BitmapImage imgSourceR =
new
BitmapImage(uriR);
this
.imageR.Source = imgSourceR;
|
Relative or Absolute URI?
Relative URI
Relative URIs specify the location of a resource file relative to the application root or the referencing XAML.
Absolute Uri
Absolute URIs specify the exact location of a resource file, and bypass the fallback mechanism.
RelativeOrAbsolute
If you are not sure whether of these two options to use you can waylays use the RelativeOrAbsolute.
For any reference you can take a look at theMSDN documentation.
You can get the full source codehere.