问题
I have some resources (images in this case) in a resource file that I use on controls in my Windows Forms project. The Visual Studio Resource Selection dialog doesn't have very good support for choosing images from resource files unless they're in specific locations, but you can edit the designer file directly, and this works just fine; the application compiles and runs correctly, and the Windows Forms Designer is smart enough to not mess up my hand-edited code.
// in an assembly named ResourceConsumer
this.button1.Image = global::ResourceConsumer.Properties.Resources.Close32x32;
Now I want to move those resources to an external assembly so they can be used by multiple applications. I can set up an assembly to expose its resources without a problem (as long as I'm using Visual Studio 2008 or later), and this works fine. When I change the designer code to reference the image from its new location, the code compiles and runs correctly, but now the Windows Forms Designer changes my code whenever it generates code; it embeds the binary of the image in the local resource file and references it from there.
// ResourceProducer is an external assembly containing resources
this.button1.Image = global::ResourceProducer.Properties.Resources.Exit32x32;
is changed by the Windows Forms Designer to:
this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image")));
The Windows Forms Designer seems to understand pulling a resource from within the same assembly, but not an external one. Is there any way to have the Windows Forms Designer allow me to use a resource from an external assembly?
回答1:
Nope, the designer doesn't support this. Important that it works the way it does, localization through satellite assemblies wouldn't work otherwise.
You can do this but you have to write the code yourself. Pretty much what you find in the Resources.Designer.cs file. Do consider if this is worth the effort, it isn't very maintainable and sharing resource assemblies isn't much of an optimization. A terabyte disk is less than a hundred bucks.
Btw: never edit the Resources.Designer.cs file yourself.
回答2:
I have the exact same problem and there may be an alternative approach, depending on your code-base. If the properties that have been modified to reference a specific resource are on custom controls, then you could add the [[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
attribute to those properties (override or hide them, if necessary) and the Designer will leave them alone.
However, if the properties are on basic UI elements (e.g. Form.BackgroundImage) then you'd have to have to override or hide those as well and I'm not sure how desirable that is.
来源:https://stackoverflow.com/questions/3619341/how-do-i-get-the-windows-forms-designer-to-use-resources-from-external-assembly