WP7 working with Images: Content vs Resource build action

来源:互联网 发布:2016nba总决赛每场数据 编辑:程序博客网 时间:2024/06/05 07:27

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 the following structure 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
<ImageStretch="None"Source="/images/appbar.cancel.rest.png"/>

C#:

?
1
2
3
4
//Content
Uri uri = newUri("/images/appbar.cancel.rest.png", UriKind.Relative); 
BitmapImage imgSource = newBitmapImage(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
<ImageSource="/WP7SampleProject3;component/images/appbar.feature.email.rest.png"/>

C#:

?
1
2
3
4
//Resource
Uri uriR = newUri("/WP7SampleProject3;component/images/appbar.feature.email.rest.png", UriKind.Relative);
BitmapImage imgSourceR = newBitmapImage(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 the MSDN documentation.

You can get the full source code here.