views:

119

answers:

1

I have a WPF control hosted in Windows Forms and I would like to access it's resources, specifically images. What is the best way to do that?

I was thinking of using a ResourceDictionary, but I'm not sure how I can access it from within a Windows Form.

+1  A: 

This is a standalone WPF control, in a DLL? There are two ways that the resources can be embedded... as part of a .resources file (e.g. the Project's "Resoruces" tab), or as files included as "Embedded Resources"...

To get the assembly reference to the DLL this is usually the easiest:

 var ass = typeof(ClassInOtherDll).Assembly;

In the Resources

If this is part of the default project resources, and not a different .resources file included inside the DLL, you can use the default base-name.

var ass = typeof(ClassInTargetDLL).Assembly;            
var rm = new ResourceManager("...BaseName...", ass);

BaseName for default project resources is : 
  C# :=  Namespace.Properties.Resources
  VB :=  Namespace.Resources

After that you can just call GetObject() and do a cast back:

var myImage = rm.GetObject("check_16");
return myImage as Bitmap;

If you want to find out whats in there, get the assembly reference and call ass.GetManifestResourceNames()

  • .resources files can be used with a ResourceManager
  • embedded resources will just show up as a list. Use the other method for these.

And this is all assuming they default culture =)

As Embedded Resources

You can use the regular methods on the assembly to get an embedded resource. You find it by name, and then Basically you will need to convert the stream back into your desired type.

GetManifestResourceNames()
GetManifestResourceStream(name)  

I usually use these like this:

// called GetMp3 in the post, but it returns a stream.  is the same thing
var stream = GetResourceStream("navigation.xml");
var reader = New XmlTextReader(stream);
return reader;

To get an image that is an embedded resource, this works for me:

var stream = GetResoureStram("check_32.png");
var bmp    = new Bitmap(stream);
this.MyButton.Image = bmp;
Andrew Backer
Yes, it is a standalone WPF control in a DLL. Also, I should have mentioned that I'm using c#. You're on the right track, can you elaberate on using the normal methods? Maybe an example? Thanks!
isorfir
Thanks for giving a great explanation of everything! Got the first example working and that should do it. What reader would I use for a .png (for the second option)?
isorfir
PNGs are Bitmaps, so that is what you convert to. Bitmap is so much more than a .BMP these days =) The example I use is real, and is a png24+alpha. I added a bit about getting a png stored as an embedded resource.
Andrew Backer