WPF controls not recognized in code-behind when using new CSPROJ format

有些话、适合烂在心里 提交于 2019-12-04 04:54:21

A slight improvement on your previous answer is to include the .g.cs files, but mark them as not visible so they do not show in the solution. You will then also need to mark the BaseIntermediateOutputPath as not visible otherwise it shows up as an empty folder.

This gives the same behaviour but looks tidier as you're not seeing the obj folder in the solution explorer.

<ItemGroup>
  <ApplicationDefinition Include="App.xaml">
    <Generator>MSBuild:Compile</Generator>
    <SubType>Designer</SubType>
  </ApplicationDefinition>
  <Page Include="**\*.xaml" SubType="Designer" Generator="MSBuild:Compile" Exclude="App.xaml" />
  <Compile Update="**\*.xaml.cs" SubType="Designer" DependentUpon="%(Filename)" />
  <Compile Include="$(IntermediateOutputPath)*.g.cs" Visible="false" />
  <None Include="$(BaseIntermediateOutputPath)" Visible="false" />
</ItemGroup>

One slightly hacky solution is to edit the project file to add the generated classes. Unfortunately, I can't work out how to make the file be DependentUpon the XAML file - I think that only works for files in the same folder.

In addition, you need to use MSBuild:UpdateDesignTimeXaml instead of MSBuild:Compile, as described here

Finally, it appears you have to explicitly name every "Include" in the "Page" element - you can't use wildcards.

<Project>
  <ItemGroup>
    <ApplicationDefinition Include="App.xaml">
      <SubType>Designer</SubType>
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
    </ApplicationDefinition>
    <Page Include="MainWindow.xaml">
      <SubType>Designer</SubType>
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
    </Page>
    <Compile Update="**\*.xaml.cs" DependentUpon="%(Filename)" />
    <!-- ADD THIS LINE HERE TO INCLUDE THE GENERATED PARTIAL CLASSES -->
    <!-- ENSURE YOU ARE USING THE g.cs AND NOT g.i.cs FILES 
         OR YOU WILL GET A BUILD FAILURE -->
    <Compile Include="$(IntermediateOutputPath)**\*.g.cs" />
  </ItemGroup>

I found that using this like to define the Sdk resolved it for me:

<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="MSBuild.Sdk.Extras">
  <PropertyGroup>
....

instead of

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
....

(This is in 15.9.15 version of VS2017)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!