13

How can I put my ViewModel file (a .cs file) folded inside its corresponded View file (a .xaml file) file like in the image?

enter image description here

GEOCHET
  • 21,119
  • 15
  • 74
  • 98

2 Answers2

17

I don't know of a way to do it in visual studio, but you can edit your .csproj file in a text editor. You should find something like this:

<Page Include="MainWindow.xaml">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
</Page>
<Compile Include="MainWindow.xaml.cs">
  <DependentUpon>MainWindow.xaml</DependentUpon>
  <SubType>Code</SubType>
</Compile>

The two tags might not be right next to each other in your file. The important part is the <DependantUpon> tag.

In your file, find the tag with the include="ViewModel.cs" attribute. Inside of this tag, add <DependantUpon>View.xaml</DependantUpon> as a child element. Now your ViewModel.cs file will always be a inside the View.xaml file. In the end, your file should have these something similar to this snippet:

<Page Include="View.xaml">
  <SubType>Designer</SubType>
  <Generator>MSBuild:Compile</Generator>
</Page>
<Compile Include="ViewModel.cs">
  <DependentUpon>View.xaml</DependentUpon>
</Compile>
Ken Wayne VanderLinde
  • 18,915
  • 3
  • 47
  • 72
  • 2
    See http://stackoverflow.com/questions/3621345/how-to-group-partial-class-files-in-solution-explorer-vs2010 for a GUI way to do this –  Feb 27 '11 at 15:34
  • Still would be nice if there was a default GUI method. Seems like an obvious thing to have from the get-go. – Ken Wayne VanderLinde Feb 27 '11 at 17:40
0

So, after a lot of try and error finally I've came up with a satisfying solution. this is an old question, but I'm gonna leave this here anyway.

If you want to all of your viewmodels nested under your views e.g. MainWindowViewModel.cs be folded inside MainWindow.xaml and these lines to your csproj

    <ItemGroup>
        <Compile Update="**\*ViewModel.cs">
            <DependentUpon>$([System.String]::Copy(%(Filename)).Replace('ViewModel', '.xaml'))</DependentUpon>
        </Compile>
    </ItemGroup>

And then unload and reload the project. now if you add any class file that has the ViewModel.cs postfix in its name, it's going to be listed under your .xaml file.

Nima Ghomri
  • 98
  • 1
  • 8