简体   繁体   中英

WPF control hosted in Windows Forms: Is it possible to access resource files?

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.

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 (eg 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM