WinForm部分类

15

我有一个WinForm项目,其中包含一个名为MainUI的表单。您可以看到自动生成的部分类显示为MainUI.cs下的节点。是否有一种方法可以将我自己创建的部分类MainUI.Other.cs“移动”到MainUI.cs下,以便它显示为另一个节点?

alt text

4个回答

14

关闭Visual Studio中的解决方案,然后在文本编辑器中打开.csproj文件。 找到MainUI.Other.cs,并添加以下XML元素:

<Compile Include="MainUI.Other.cs">
  <SubType>Form</SubType>
  <DependentUpon>MainUI.cs</DependentUpon>  <!-- this is the magic incantation -->
</Compile>

重新在Visual Studio中打开解决方案,享受子节点的好处。

话虽如此,您可能需要重新考虑这是否是一个好主意。 .designer.cs文件显示为子节点的原因是因为通常您不需要或不想打开它,因为它包含生成的代码,您通常会通过设计器查看或编辑该代码。 而部分类文件将包含您的代码,您将要编辑和查看它;如果该文件在“解决方案资源管理器”中不易见,则可能会令维护程序员感到困惑。 不过,只有您才知道对于您的项目来说什么是正确的--这只是需要记住的事情!


请注意 - 如果您的“DependentUpon”文件位于子文件夹中,则即使在其他地方显示为<Compile Include =“Subfolder \ filename”>,您仍应该只使用<DependentUpon>filename </ DependentUpon>。 - Filip Skakun

1

是的,这是可能的,但您将不得不手动编辑项目文件。

在项目文件中(使用 XML 编辑器打开),找到文件列表项组。在我的示例中,我将表单保留为“Form1.cs”。按照以下示例将子元素"<DependentUpon>"添加到您的扩展类:

 <Compile Include="Form1.cs">
      <SubType>Form</SubType>
    </Compile>
    <Compile Include="Form1.Designer.cs">
      <DependentUpon>Form1.cs</DependentUpon>
    </Compile>
    <Compile Include="Form1.Designer.Other.cs">
      <DependentUpon>Form1.cs</DependentUpon>
      <SubType>Form</SubType>
    </Compile>

通常情况下,您不希望任何非生成代码被隐藏为子节点。我的正常做法是在项目中创建一个名为“Partial Classes”的文件夹,并将它们全部添加到同一位置。

0
只是为了补充@itowlson的答案:如果在编译时出现“包含重复的'Compile'项”的错误,那么很可能是因为你告诉它要使用通配符来包含的文件已经被包含了。
解决方案是将它们从编译配置中删除,然后再添加回去,像这样:
</Project>
  <ItemGroup>
    <Compile Remove="MainUI.Other1.cs" />
    <Compile Remove="MainUI.Other2.cs" />
  </ItemGroup>
  <ItemGroup>
    <Compile Include="MainUI.Other1.cs">
      <DependentUpon>MainUI.cs</DependentUpon>
    </Compile>
    <Compile Include="MainUI.Other2.cs">
      <DependentUpon>MainUI.cs</DependentUpon>
    </Compile>
  </ItemGroup>
</Project>

0

您可以修改项目源文件以将相关文件分组。 在项目源文件中,找到包含MainUI.cs的ItemGroup元素,并为MainUI.Others.cs添加一个条目。

这里有一篇博客文章详细介绍如何操作。 分组/嵌套源代码文件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接