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

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

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

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

怎么了?


当前回答

这有一个非常具体的原因,它在项目设置中。当您试图将WPF控件/窗口添加到. net 2.0类库或项目中时,通常会发生这种情况。出现此错误的原因是项目不知道它正在构建WPF控件或窗口,因此试图将其作为c# 2.0项目构建。

解决方案涉及编辑.csproj文件。右键单击引起问题的项目,选择“卸载项目”。右键单击未加载的项目并选择“Edit .csproj”。将打开.csproj文件,您可以看到XML。看看下面这行:

<Import Project=…..

它在文件的末尾,你仅有的一行大概是

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />

这告诉Visual Studio将项目构建为. net 2.0项目。我们要做的是告诉Visual Studio这实际上是一个WPF项目,所以我们必须添加以下一行:

<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />

这一行将告诉Visual Studio将项目构建为WPF项目。现在你的.csproj文件底部应该是这样的:

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />

保存.csproj文件,在解决方案资源管理器中右键单击它,并选择“重新加载项目”编译,就是这样,您都完成了!

其他回答

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

  <PropertyGroup>
    <UseWPF>true</UseWPF>

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

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

这发生在我身上,因为一个Nuget包卸载程序吹走了App.xaml中<Application>元素上的所有属性。这包括x:Class属性,它指定应用程序类名。因此从未生成包含InitializeComponent()方法的分部类。

我通过将App.xaml恢复到源控制副本来解决这个问题。

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

I know this was answered due to a different cause, but this is a highly hit posting and I had ran into the same issue with a class library. In this case, it turned out to be both a change in my namespace (answered in this post here) and that the compiler could not rebuild the Window.g.i.cs which defines the InitializeComponent() method. It couldn't because the class library was missing the ProjectTypeGuid value for WPF projects in the csproj file. Instructions for this are here and here. I thought I would share in case someone else has run into the same issue. Just changing the namespace isn't enough in this case.

我有同样的问题,期望我把我的主窗口xaml和cs复制到一个新文件,然后把它们复制回原来的地方。在尝试编译WPF应用程序后,我得到了这个错误。

我修复这个错误的方法是重命名命名空间(from egNamespace -> egNamespaceNew),它再次工作。然后我将名称空间改回原来的名称空间。