如果我在Visual Studio 2010 SP1中创建一个新项目,并选择“WPF应用程序”,并尝试构建生成的应用程序,我会得到错误
名称“InitializeComponent”在当前上下文中不存在。
今天早上,当我试图构建当前项目时,我遇到了类似的错误。昨天,我编译和运行它没有问题。
我创建了一个新项目,每当我编译项目时,都会得到错误。我刚刚把项目发给了同事,他刚刚编译完成,没有任何错误。
怎么了?
如果我在Visual Studio 2010 SP1中创建一个新项目,并选择“WPF应用程序”,并尝试构建生成的应用程序,我会得到错误
名称“InitializeComponent”在当前上下文中不存在。
今天早上,当我试图构建当前项目时,我遇到了类似的错误。昨天,我编译和运行它没有问题。
我创建了一个新项目,每当我编译项目时,都会得到错误。我刚刚把项目发给了同事,他刚刚编译完成,没有任何错误。
怎么了?
当前回答
OK this.InitializeComponent();
Wrong this.InitializeComponent;
其他回答
这为我解决了问题。
我已经注释掉了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
}
导致这个错误的另一个常见原因是:
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."
在我的情况下,我的项目中有一个错误的引用,但没有报告。
我通过阅读我所有的推荐信来解决我的问题,即使它们是正确的。
我同意上面的答案,即名称空间必须匹配。但是,我遇到了这样一个问题,即名称空间匹配。
为了解决这个问题,我简单地将XAML中的名称空间更改为不正确的名称空间,保存,然后将其更改为正确的名称空间。瞧!
另一种可能的解释是,您正在针对x86进行构建。右键单击解决方案并选择配置管理器。看看你是否在x86而不是任何CPU上构建。