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

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

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

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

怎么了?


当前回答

在我将一个新的平台“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.

其他回答

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

它总是有效的。

OK     this.InitializeComponent(); 

Wrong  this.InitializeComponent;

当您从另一个项目导入类,或更改xaml文件的路径,或xaml或.cs文件后面的名称空间时,可能会出现此错误。

第一:它的名称空间可能与新项目中的名称空间不相同

namespace TrainerB.MVC.Forms
{
     public partial class AboutDeveloper : ContentPage
     {
          public AboutDeveloper()
          {
               InitializeComponent();
          }
     }
}

正如您所看到的,导入文件中的名称空间以旧的项目名称开始:“TrainerB”,但您的新项目可能有不同的名称,所以只需在.xaml文件和后面的.cs文件中将其更改为正确的新项目名称。

Two:

将.xaml文件的属性更改为:

构建动作:嵌入式资源

自定义工具:MSBuild:UpdateDesignTimeXaml

我同意上面的答案,即名称空间必须匹配。但是,我遇到了这样一个问题,即名称空间匹配。

为了解决这个问题,我简单地将XAML中的名称空间更改为不正确的名称空间,保存,然后将其更改为正确的名称空间。瞧!

在我的案例中(NET Core 3.1),我通过在项目文件的ProjectGroup部分中给它一个AssemblyName标记来修复它。如。

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWPF>true</UseWPF>
    <AssemblyName>ProjectNameUsually</AssemblyName>
  </PropertyGroup>
  ...
</Project>

这也修复了编译器在代码背后看不到x:Name控件的问题。