【问题标题】:Dotnet build fails for projects containing UserControl (InitializeComponent does not exist in the current context)包含 UserControl 的项目的 Dotnet 构建失败(InitializeComponent 在当前上下文中不存在)
【发布时间】:2018-09-20 09:13:18
【问题描述】:

我有一个使用 .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 build 从命令行构建时,构建失败并出现我之前在 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>

【问题讨论】:

  • 这个项目完全不适合.NETCore,用dotnet.exe构建没有意义。使用 msbuild。
  • @HansPassant 我尝试这样做的原因是因为我正在尝试设计可以在不同解决方案中重复使用的构建内容;我宁愿不解析 .csproj 来确定要使用的构建工具。当你说它不合适时,这是否意味着它完全不兼容?另外,我认为 dotnet build 是在后台运行 MSBuild - 不是这样吗?
  • @ket,这个问题有什么更新吗?你解决了这个问题吗?如果没有,请告诉我有关此问题的最新信息吗?
  • @Leo Liu-MSFT,对不起,我忽略了接受你的回答。感谢您的澄清。

标签: c# wpf visual-studio build msbuild


【解决方案1】:

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

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

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

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

更多详情请见XAML files are not supported。

【讨论】:

  • 从 VS 16.1 开始应该支持这个,但我仍然有同样的问题(在 VS 16.2 中)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
  • 2021-09-03
  • 2012-08-03
  • 2011-10-19
  • 2016-06-01
  • 2018-06-06
相关资源
最近更新 更多