最近我也遇到了同样的问题。查看了微软的文档,但是没有找到好的解决方案。最终,我通过下面描述的方法让WinForms设计器中的图像编辑器识别其他项目中的资源文件。这种方法很巧妙——如果有人有更简洁的解决方案,请发表。我只在VS 2008上进行了测试。
在开始之前,我应该说,如果你只想让Resources.resx文件中的项对其他项目可用,你可以编辑它的属性,并将生成的类的访问修饰符设置为public,这样它就使用PublicResXFileCodeGenerator。下面的操作仅在你想要像Douglas在上面的帖子中描述的那样使WinForms设计器拾取此资源文件中的图像时才需要。
假设你的解决方案具有以下布局。各个项目的默认命名空间(在解决方案资源管理器中单击项目节点,然后右键单击->属性->应用程序选项卡)在这里非常重要,因此我已经将其放在了项目名称后面的括号中。
- MySolution
- SharedProject (默认命名空间=SharedProject)
- SharedProject.csproj
- WinFormsProject1 (默认命名空间=WinFormsProject1)
- WinFormsProject1.csproj
- WinFormsProject2 (默认命名空间=WinFormsProject2)
- WinFormsProject2.csproj
你想在SharedProject中创建一个资源文件,其中包含可以被WinFormsProject1和WinFormsProject2使用的图像。
首先,在SharedProject的根目录中创建一个新的资源文件,我们称之为SharedResources.resx。这个文件使用ResXFileCodeGenerator而不是PublicResXFileCodeGenerator非常重要,原因将在后面变得清晰明了。
在Visual Studio中编辑SharedResources.resx并添加你想要共享的图像资源。Visual Studio还应该在SharedProject中为你生成一个名为SharedResources.designer.cs的类文件。
现在,你的解决方案应该如下所示:
- MySolution
- SharedProject (默认命名空间=SharedProject)
- SharedProject.csproj
- SharedResources.resx
- SharedResources.Designer.cs
- WinFormsProject1 (默认命名空间=WinFormsProject1)
- WinFormsProject1.csproj
- WinFormsProject2 (默认命名空间=WinFormsProject2)
- WinFormsProject2.csproj
如果你用文本编辑器打开SharedProject.csproj,你应该看到以下条目:
<EmbeddedResource Include="SharedResources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>SharedResources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<Compile Include="SharedResources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>SharedResources.resx</DependentUpon>
</Compile>
现在您需要使资源在WinFormsProject1中可访问。为此,您需要在文本编辑器中编辑WinFormsProject1.csproj,因为您需要设置的某些属性未在Visual Studio中公开。
打开WinFormsProject1.csproj文件,并在ItemGroup中添加以下内容:
<Compile Include="..\SharedProject\SharedResources.Designer.cs">
<Link>SharedResources.Designer.cs</Link>
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>SharedResources.resx</DependentUpon>
</Compile>
<EmbeddedResource Include="..\SharedProject\SharedResources.resx">
<Link>SharedResources.resx</Link>
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>SharedResources.Designer.cs</LastGenOutput>
<CustomToolNamespace>SharedProject</CustomToolNamespace>
<LogicalName>SharedProject.SharedResources.resources</LogicalName>
</EmbeddedResource>
重点是CustomToolNamespace和LogicalName。默认情况下,Visual Studio使用项目的默认命名空间来命名资源并生成*. Designer.cs文件。由于SharedProject和WinFormsProject1具有不同的默认命名空间,因此默认行为会导致嵌入在WinFormsProject1中的资源与SharedProject内部的*. Designer.cs文件不兼容。可以通过覆盖CustomToolNamespace和LogicalName来预防这种情况。
现在对WinFormsProject2.csproj执行相同操作。返回Visual Studio。它会注意到您已更改csproj文件并要求重新加载项目-选择“重新加载”。您应该发现在设计WinFormsProject1和WinFormsProject2中的表单时,现在可以从SharedResources.resx选择图像。
本质上,所有这些都是使VS包括SharedProject中的SharedResources.resx文件在WinFormsProject1和WinFormsProject2项目中。只有一个.resx源文件(在SharedProject中),但编译解决方案时实际上将有三个完全相同的类,称为SharedProject.SharedResources,在三个程序集中各有一个,但由于所有内部可见性,即使在项目之间添加引用也不会互相干扰。