Search code examples
c#wpfxamlcsprojaddchild

How to connect xaml to it's xaml.cs using code


I'm creating a file generator which also adds to the changed, not current project's csproj file the added files for automatic include.

all files (like cs files) work fine, however, I don't understand how to use this API to create a child to the build.

currently, my code adds the files to the build but the xaml cs and the xaml are connected but visually seperated (the xaml cs file is not inside the xaml file)

my code is the following: (input.FolerPath is the solution path)

public void Execute(GeneratorInput input)
{
    var p = new Microsoft.Build.Evaluation.Project(input.FolderPath + ".csproj");
    p.AddItem("Compile", "SomePath.cs"); // this works given a proper path
    p.AddItem("Compile", "XamlCsPath.xaml.cs"); // this works for the xaml cs
    p.AddItem("Page", "XamlPath.xaml"); // this creates the xaml file seperately
}

Ultimately, what I want to achieve is the following csproj file:

<Compile Include="XamlCsFile.xaml.cs"> // I got this far
    <DependentUpon>XamlFile.xaml</DependentUpon> // this is what I am trying to add
</Compile>

Solution

  • This seems to do the trick:

    var element = p.AddItem("Compile", "XamlCsPath.xaml.cs"); // this works for the xaml cs
    element[0].SetMetadataValue("DependentUpon", "XamlFile.xaml");