Grouping files in Visual Studio
A quick tutorial on how to nest/group files within Visual Studio using the <DependentUpon> property in a project file.

Anyone who has worked with Visual Studio will have noticed that the IDE has a way of grouping related files within a single item in the project explorer.

This arises in a number of common situations:

  • The grouping of Form.cs and Form.Designer.cs in WinForms projects.
  • The grouping of Window.xaml and Window.xaml.cs in WPF projects.
  • The grouping of Page.aspx and Page.aspx.cs in pre-MVC ASP.NET projects.

As an example, we can see that MainForm.cs is grouped with MainForm.Designer.cs in this simple WinForms project:

An example Visual Studio containing grouped files

But how do we do this ourselves?

OK, this is a great feature, but it'd be neat if we could do it ourselves, too. Luckily, we can!

For a worked example, let's say we have a class that is broken down into a number of files, each containing a partial class with a subset of functionality from the main class.

A Visual Studio solution with a number of distinct files

If we open up the .csproj file, we can see that this is set out as follows:

<Compile Include="ExampleClass.cs" />
<Compile Include="ExampleClass.Partial1.cs" />
<Compile Include="ExampleClass.Partial2.cs" />
<Compile Include="ExampleClass.Partial3.cs" />

To group all of the partial classes underneath the main class, all we have to do is add a DependentUpon attribute to the elements we want to group. I'll let the XML speak for itself:

<Compile Include="ExampleClass.cs" />
<Compile Include="ExampleClass.Partial1.cs">
  <DependentUpon>ExampleClass.cs</DependentUpon>
</Compile>
<Compile Include="ExampleClass.Partial2.cs">
  <DependentUpon>ExampleClass.cs</DependentUpon>
</Compile>
<Compile Include="ExampleClass.Partial3.cs">
  <DependentUpon>ExampleClass.cs</DependentUpon>
</Compile>

This gives us the following result - exactly what we wanted:

A Visual Studio solution with a number of grouped files


Posted by Matthew King on 14 March 2014
Permission is granted to use all code snippets under CC BY-SA 3.0 (just like StackOverflow), or the MIT license - your choice!
If you enjoyed this post, and you want to show your appreciation, you can buy me a beverage on Ko-fi or Stripe