I'm looking at tidying up my project layout in Visual Studio and I'm wondering if there is any hack, plugin or trick to associate an .xml file with a .cs file of the same name so they appear grouped in my solution navigator/explorer.
Similar to the way the code-behind file is associated with its aspx.
Any suggestions welcome. Thanks
In your project file :
<Compile Include="FileA.cs"/>
<Compile Include="FileA.xml">
<DependentUpon>FileA.cs</DependentUpon>
</Compile>
Or you could use Group Items
command of VSCommands 2010 extension.
Edit: Just in case your file is in a folder, don't include the folder name in DependentUpon
tag. For example if your file is in Helpers
folder:
<Compile Include="Helpers\FileA.cs"/>
<Compile Include="Helpers\FileA.xml">
<DependentUpon>FileA.cs</DependentUpon>
</Compile>
If you do not want to slow down you IDE with heavy and proprietary VSCommands extension you can use small extension NestIn instead. It can nothing but group/ungroup files
For the simple case where the file is a "top level" file, Julien's description works perfectly. However, in the case where the DependentUpon file is in a Folder under the project, this looks different. I personally don't like it because it seems like it could lead to ambiguity, but that's an opinion.
<Compile Include="DataStructs\CKDTree.cs" />
<Compile Include="DataStructs\CClosestObjects.cs" >
<DependentUpon>CKDTree.cs</DependentUpon>
</Compile>
Notice that the dependent item does NOT include the Folder of the parent. This is true in VS2013... probably true in earlier versions but I have not verified it.
Not sure if people are aware, but nesting files like this seemingly breaks VS's ability to rename the root file, at least when your new nested file is also a partial class. For instance here's the tree we created...
MainWindow.xaml
MainWindow.xaml.cs
MainWindow.Commands.cs
MainWindow.Commands.cs is just another partial class of MainWindow, same as MainWindow.xaml.cs. However, if you then try and rename MainWindow.xaml, instead of automatically renaming the dependent files, it throws an exception.
For completeness, I also tried naming the file MainWindow.xaml.Commands.cs
but that didn't work either.
Without the extra 'commands' file, rename works fine, of course.
MainWindow.xaml
MainWindow.xaml.cs
Anyway, this was reason enough for us to abandon nesting files like this. Without the ability to rename, it's just not worth it.
File Nesting extension for visual studio is a good one. It has about 500K downloads at the time of writing this answer. I added it personally to my VS 2015 and it was working fine (haven't tried it with VS 2017 yet).