wpfvisual-studioxamlcode-behind

How to 'merge' a XAML file and its code-behind with Visual Studio


I have a template defined in a XAML file named 'MyTemplate.xaml'. This template is using a code-behind file named 'MyTemplate.cs'.

Mytemplate.xaml:

<ResourceDictionary x:Class="Project.Templates.MyTemplate">
    <DataTemplate ... />
</ResourceDictionary>

MyTemplate.cs:

namespace Project.Templates
{
    public partial class MyTemplate : ResourceDictionary
    {
        ...
    }
}

In the Visual Studio Solution Explorer, these two files are side by side. What I would like to do is to put these two files together, just like with a Control and its code-behind.

What I have: enter image description here

What I would like to have: enter image description here

What is the best way to do that? Thank you.


Solution

  • You need to edit the .csproj file. Find the <Compile> element for MyTemplate.cs, and add a <DependentUpon> element under it:

    <Compile Include="MyTemplate.cs">
      <DependentUpon>MyTemplate.xaml</DependentUpon>
    </Compile>
    

    See this blog post: make a project item a child item of another