views:

173

answers:

1

Hello

My motivation for this question is really just to specify an image to be used in a user control via a dependency property for ImageSource. I'm hitting some pain points involving the management, access, and unit testing for this.

  • Is the resource editor a good tool to use to maintain images for the application?
  • What is the best way to translate the Bitmap from the editor to an ImageSource?
  • How can I grab the resource Filename from the editor?

Cheers,
Berryl

+1  A: 

No, the resource editor is not a good tool for this.

In a WPF application the best way is to put all of your images in an "Images" directory and mark each one as a "Resource". Then you can reference them directly in Image controls and elsewhere.

Here are the precise steps:

  • Crop and otherwise adjust your images using your favorite bitmap editing program (Paint.NET, Photoshop, etc)
  • Save them as .png files (or .jpg or .gif if you prefer)
  • Create an "Images" folder inside your Visual Studio solution (or multiple folders, however you want to organize it)
  • Drag the images from your hard disk into your "Images" folder (or right-click the project, select New -> Existing Item and select the images)

Now you can reference your images easily in XAML:

<Image Source="Images/MyImage.png" />

Or in code:

var source = (BitmapSource)Application.LoadComponent(
               new Uri("Images/MyImage.png", UriKind.Relative));

You can also reference images in external assemblies:

<Image Source="ReferencedAssembly;v1.0.0.1;component/Images/MyImage.png" />

Which in code would be:

var source = (BitmapSource)Application.LoadComponent(
               new Uri("ReferencedAssembly;v1.0.0.1;component/Images/MyImage.png",
                 UriKind.Relative));
Ray Burns
Perfect! Two questions - (1) any practical advantage to having the build action be 'Content' over 'Resource'? (2) Would the code to get at in a referenced assembly, just be 'Application.LoadComponent("ReferencedAssembly;v1.0.0.1; component/Images/MyImage.png") as BitmapSource;'? Do you know of any helper code to get that syntax (sorry, three questions)?? Thanks!
Berryl
It looks like Application.LoadComponent takes a Uri (not a string)
Berryl
Thanks. Somehow I always forget the "new Uri(..., UriKind.Relative)" until the compiler points out the error of my ways. I have corrected the answer.
Ray Burns
"Resource" adds the file to your .exe or .dll. "Content" stores the file as a separate file in your output directory. It is usually easier to deploy a single .exe file, but if you have huge image files or hundreds of them it may be better to use Content instead.
Ray Burns