Is it possible to connect xaml.cs to corrsponding xaml in VS2017 csproj format?

Viewed 453

Because of huge advantages in NuGet packaging, I transformed the csproj file of a C# library to the new Visual Studio 2017 format as described here: Old csproj to new csproj: Visual Studio 2017 upgrade guide.

Now all the xaml.cs and xaml files of my WPF usercontrols are being shown separatedly side by side and not in a structure (xaml.cs "inside" xaml). Additionally I can not switch between them via the context menu commands "view code" or "view designer".

I found out that I can solve the structural display with adding appropriate entries in the csproj file:

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

After having saved the csproj file, it takes a second or two and then the two items are visually structured in the project explorer view. I still cannot switch between them via context menu commands, though.

Additionally I get the error NETSDK1022 when compiling, telling about those compile elements being doubled now (the new project format automatically adds all suitable files). It is possible to disable this mechanism via setting EnableDefaultCompileItems to false, which works.

Is there a better way to "bind" the xaml and it's code-behind file for the new VS2017 project format?

(maybe this is one of the issues why the new project format is not yet released for window projects...)

2 Answers

Replace Include with Update.

Starting from your point

the new project format automatically adds all suitable files

Because this point, usually prefer to use Update instead of Include. Just this.

Assuming all files are included by default, when you use the word "Include", you are adding a file that already exists. But if you use the word "Update", you update the file that is already included.

I don't think switching to the new project format is officially supported for WPF projects targeting the .NET Framework. It will be supported in Visual Studio 2019 when you target .NET Core 3 though.

There is this new Microsoft.NET.Sdk.WindowsDesktop SDK that builds .NET Core WPF projects including XAML files using the following minimal .csproj file available in the preview:

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
    <PropertyGroup>
        <OutputType>WinExe</OutputType>
        <TargetFramework>netcoreapp3.0</TargetFramework>
        <UseWPF>true</UseWPF>
    </PropertyGroup>
</Project>

Please refer to this blog post for more information.

Related