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

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

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

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

怎么了?


当前回答

如果您正在使用Xamarin Forms,并且您移动了一个XAML文件,那么该文件的“构建操作”将被更改。Xamarin Forms要求“构建动作=嵌入式资源”。

在Visual Studio中应用“build action”:

选择XAML文件-> Properties -> Build Action = Embedded Resource

其他回答

在一些操作之后,.cs文件的命名空间和。xaml文件中的命名空间可能是不同的(在xaml中查找x:Class="namespace. yourtype ")。

使它们相同。

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

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指向你的命名空间(app文件所在的位置)+ .App 如。 x: Class = " DX。App" <===确保这是App而不是主页名

希望这也适用于你。

这为我解决了问题。

我已经注释掉了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,这是我的问题。 我在文件夹外创建了相同的控件,就是这样。