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

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

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

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

怎么了?


当前回答

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

它总是有效的。

其他回答

我尝试了上面所有的建议。如果你太努力而没有成功,那就走更容易的路。创建一个新页面。xaml然后复制新类的代码并删除有问题的类xaml。不要花更多的时间。

导致这个错误的另一个常见原因是:

Right click on folder in project to create new UserControl. This creates a class and xaml file that derives from user control in the namespace of the folder. Then you decide to change the namespace of the class because you're really just using folders for organization of code. The x:Class attribute will not get automatically updated so it will be searching for a class that doesn't exist. Could probably use a better error message like "x:Class type could not be found in namesace bla.blaa.blaaa."

这为我解决了问题。

我已经注释掉了App.xaml文件中的资源

<Application x:Class="MyApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Application.Resources>
    <!--<ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary
            Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>-->
  </Application.Resources>
</Application>

将此注释回来以修复构建错误。

<Application x:Class="MyApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Application.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary
            Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>
</Application>

深入挖掘一下,我发现{Project}\obj\debug中的app.g.cs文件在我留下资源注释时只包含以下内容。

/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
    if (_contentLoaded) {
        return;
    }
    _contentLoaded = true;
    System.Uri resourceLocater = new System.Uri("/MyApp;component/app.xaml", System.UriKind.Relative);

    #line 1 "..\..\..\App.xaml"
    System.Windows.Application.LoadComponent(this, resourceLocater);

    #line default
    #line hidden
}

右键单击项目中的文件夹以创建新的UserControl,这是我的问题。 我在文件夹外创建了相同的控件,就是这样。

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