包含UserControl的项目的Dotnet构建失败(InitializeComponent在当前上下文中不存在)

时间:2018-04-10 16:42:22

标签: c# wpf visual-studio build msbuild

我有一个使用.NET Core格式定义的.csproj项目。该项目包含由.xaml文件和关联的.cs文件组成的用户控制文件。以前我在这些用户控件上遇到了编译错误,直到我将以下内容添加到.csproj文件中:

  <ItemGroup>
    <Page Include="**\*.xaml">
      <SubType>Designer</SubType>
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
    </Page>
    <Compile Update="**\*.xaml.cs" SubType="Code" DependentUpon="%(Filename)" />
  </ItemGroup>

此时,解决方案开始在Visual Studio中编译。但是,当我尝试使用dotnet构建从命令行构建时,构建失败并出现我之前在Visual Studio中看到的错误:The name 'InitializeComponent' does not exist in the current context.

为什么解决方案为什么在VS2017中构建但不使用dotnet构建,或者我如何解决这个问题?

编辑:没有PackageReferences的.csproj内容

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <LanguageTargets>$(MSBuildToolsPath)\Microsoft.CSharp.targets</LanguageTargets>
    <TargetFramework>net45</TargetFramework>
    <IsPackable>true</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <Page Include="**\*.xaml">
      <SubType>Designer</SubType>
      <Generator>MSBuild:UpdateDesignTimeXaml</Generator>
    </Page>
    <Compile Update="**\*.xaml.cs" SubType="Code" DependentUpon="%(Filename)" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
    <Reference Include="System" />
    <Reference Include="System.ComponentModel.DataAnnotations" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xaml" />
    <Reference Include="WindowsBase" />
  </ItemGroup>
</Project>

1 个答案:

答案 0 :(得分:3)

  

包含UserControl的项目的Dotnet构建失败(InitializeComponent在当前上下文中不存在)

此时,我恐怕你必须使用MSBuild cli而不是使用dotnet build。那是因为此时dotnet cli不支持XAML文件。 MS团队正在努力解决这个问题。

虽然,但新的sdk csproj(net461)在编译和部署之后仍可正常工作,但Visual Studio在开发期间无法解析.xaml文件,因为它需要.NET核心视图。

因此,要解决此问题,您可以使用MSBuild cli而不是dotnet构建。

有关详细信息,请参阅XAML files are not supported