如果我在Visual Studio 2010 SP1中创建一个新项目,并选择“WPF应用程序”,并尝试构建生成的应用程序,我会得到错误

名称“InitializeComponent”在当前上下文中不存在。

今天早上,当我试图构建当前项目时,我遇到了类似的错误。昨天,我编译和运行它没有问题。

我创建了一个新项目,每当我编译项目时,都会得到错误。我刚刚把项目发给了同事,他刚刚编译完成,没有任何错误。

怎么了?


当前回答

我在使用迁移向导将。net461项目迁移到新的sdk风格的csproj格式时遇到了这个问题。我必须把这个添加到我的csproj:

  <PropertyGroup>
    <UseWPF>true</UseWPF>

然后删除从迁移向导生成的任何Page标记……

<Page Include="Views\MyCustomControl.xaml">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
</Page>

其他回答

我也有同样的问题,但对我来说,这些都没用。在我的情况下,我拥有的每个WPF项目(包括新创建的项目)都停止编译此错误。最后,我卸载了所有的。net框架,然后重新安装了它们,一切又开始工作了。我还重新安装了Visual Studio,但结果没有影响。

上面的答案对我都没用。除了那些重复的我都试过了。然而,由于一些奇怪的原因,这在我的Visual Studio 2015的跨平台项目中起作用:

在“解决方案资源管理器”中右键单击导致问题的项目。在弹出菜单中选择:Add——> Class 选择跨平台——> Forms Xaml Page。保持漂亮的Page1.cs标准名称并单击Add。 注意前面的InitializeComponent()问题是如何由于某种原因消失的。 删除新创建的Page1.cs并继续编程,就像Visual Studio工作正常一样。

.xaml文件的构建动作也必须设置为“Page”,当在项目之间移动xaml文件时,这个设置会丢失(至少在VS 2010中是这样)。

帮助我的是将.csproj中的第一行更改为

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

在我将一个新的平台“x86”添加到解决方案配置管理器后,我也有这个错误消息。之前它只有“任何CPU”。解决方案仍在运行,但在错误窗口中显示了多个此类错误消息。

I found the problem was that in the project properties the 'Output Path' was now pointing to "bin\x86\Debug". This was put in by Configuration Manager at the add operation. The output path of the 'Any CPU' platform was always just "bin" (because this test project was never built in release mode), so the Configuration Manager figured it should add the "\x86\Debug" by itself. There was no indication whatsoever from the error messages that the build output could be the cause and I still don't understand how the project could even run like this. After setting it to "bin" for all projects in the new 'x86' configuration all of the errors vanished.