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

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

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

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

怎么了?


当前回答

我遇到过几次这种情况,但总是忘记是什么原因造成的。 当我在文件后面的代码上重命名命名空间时,我遇到了这个问题,但不是在XAML中。

所以检查一下你是否做了同样的事情。

名称空间和类名需要匹配,因为它们都是部分类的一部分

namespace ZZZ
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
         //...
    }
}

<!-- XAML -->
<Window x:Class="ZZZ.MainWindow">

其他回答

我知道这是一个老问题了,但我们也遇到过类似的问题。我们能够使用VS2012构建一个项目,但不能从命令行使用msbuild。我进入。proj文件,并注意到它在默认的“PropertyGroup”部分下没有“ProjectTypeGuids”的记录,所以我添加了这个:

<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

这是WPF的项目GUID。然后我删除并重新添加UserControl,它开始工作。我不确定我是否必须做最后一步,但现在它对我有用。

导航到解决方案目录 删除\obj文件夹 重新构建解决方案

我在重构过程中遇到了这个错误,我重命名了一些文件/文件夹,并且需要重新生成预先存在的*.g.cs文件。

我的方法是关闭解和删除”。解决方案路径下的Vs "文件夹。 (它会让你丢失所有的编辑器状态-打开的文件列表,窗口位置和错误缓存)

它总是有效的。

在我的情况下,程序实例已经在后台运行。我只是停止运行实例和程序构建成功。

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.