[wpf] The name 'InitializeComponent' does not exist in the current context

If I create a new project in Visual Studio 2010 SP1 and select "WPF Application" and tries to build the generated application, I get the error

The name 'InitializeComponent' does not exist in the current context.

I got a similar error this morning when I tried to build my current project. Yesterday, I had no problem compiling and running it.

I created a new project and got the error whenever I compiled the project. I have just sent the project to a colleague, and he has just compiled without any errors.

What is wrong?

The answer is


For those who find this on the internet. Check the Windows.csproj file if the compilation is there. There should be 2 entries

<Page Include="YourFile.xaml">
  <SubType>Designer</SubType>
  <Generator>MSBuild:Compile</Generator>
</Page>

<Compile Include="YourFile.xaml.cs">
  <DependentUpon>YourFile.xaml</DependentUpon>
</Compile>

I had this error messages too after I added a new platform 'x86' to the Solution Configuration Manager. Before it had only 'Any CPU'. The solution was still running but showed multiple of these error messages in the error window.

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.


Another solution to this problem is to simply change the property-> Build Action on the XAML from Embedded Resource to anything else, save, then change it right back to Embedded Resource. The error goes away.


I agree with the answer above that the namespaces have to match. However, I had a problem like this where the namespaces matched.

To fix, I simply changed the namespace in the XAML to an INCORRECT one, saved, then changed it back to the CORRECT one. Voila!


I had the same issue, I had to convert my shared project into a portable class library.


Because of some reason after copying .xaml and it's .cs between projects the build action is sometimes changing. Please make sure build action of your .xaml is Page.


Additional option:

In my case with Xamarin Forms, on top of the 'InitializeComponent' does not exist in the current context error in my App.xaml file, I also noticed in the output that the .csproj file was failing to build. Weird.

Nothing in the file itself stood out to me except these two ItemGroup entries:

  <ItemGroup>
    <EmbeddedResource Remove="App.xaml" />
  </ItemGroup>

  <ItemGroup>
    <ApplicationDefinition Include="App.xaml" />
  </ItemGroup>

I removed both from the .csproj file, performed a clean and rebuild and the error finally disappeared. So painful resolving the issue, maybe this will help someone else avoid a bit of stress down the road.


In my case (NET Core 3.1) I fixed it by giving it an AssemblyName tag in the ProjectGroup section of the project file. e.g.

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

This also fixed a problem it was having with the compiler not seeing a control by its x:Name in the code-behind.


I have discovered that the "Startup object" was (Not set) causing this error for me.

"Startup object" (Not set)


yeap, so many things can be... I would add this one... make sure the App.xaml points to your Namespace (where your app file is) + .App eg. x:Class="DX.App" <=== make sure this is App and not the Main Page name

Hope this works for you too.


None of the above answers worked for me. I tried them all except the duplicate ones. However for some weird reason this worked in my cross-platform project in Visual Studio 2015:

  1. Right-click the project that is causing the problem in the Solution Explorer. In the pop-up menu choose: Add --> Class
  2. Select cross-platform --> Forms Xaml Page. Keep the pretty Page1.cs standard name and click Add.
  3. Notice how the previous InitializeComponent()-problem just disappeared for some reason.
  4. Delete the newly created Page1.cs and continue programming as if Visual Studio was working just fine.

Check the Designer file.

I had this same issue. In my case, the cause was that the namespace for FileName.Designer.cs did not match the (correct) namespace used in FileName.cs.

Changing the namespace of FileName.Designer.cs to match that of FileName.cs solved the problem immediately.


In my case the instance of program was already running in background. I just stop the running instance and program built successfully.


If the Namespaces are correct then also there is a same error,

Just close your application and open it again.

This may solve your problem


This solved it for me.

I had commented out the resources in the App.xaml file

<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>

Commenting thiis back in to fixed the build error.

<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>

Digging a bit deeper I found that the app.g.cs file in {Project}\obj\debug only contained the following when I left the resource commented in.

/// <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
}

What helped me - is to change first line in .csproj to

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

This issue happened for me when creating a "WPF Application Project" then changing its build target to "Class Library" to be used as an external tool by another program.

I changed all my .xaml files for my windows so their build action were set to "Page". What I did not realize was that that the project also contained "App.xaml" and "App.xaml.cs".

"App.xaml" needs to be set to "Page" as well, or deleted altogether (along with "App.xaml.cs"). I did the former, then the latter as I realized the files were useless.


Another common cause of this error is if you did something in this:

  1. 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.

  2. 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."


I try all suggestions above. If you try too without success get the more easy way. Create a new page.xaml then copy your code for new class and delete class XAML with problems. Don't spend more time.


Unload the entire solution and then reload it again. Then Rebuild the solution. This resolved the issue for me.


Right click on folder in project to create new UserControl that was the problem for me. I created the same control out side the folder and that was it.


I had the same problem in VS2017, Xamarin.Forms project. Reading this bug link:

https://bugzilla.xamarin.com/show_bug.cgi?id=33181#c53

To solve the problem in this case: Right-click on [xaml-file-name].xaml, choose Properties, then change the Build Action to Content then back to Embedded resource.


If you are using Xamarin Forms and you move a XAML file the "build action" of the file is changed. Xamarin Forms requires "build action = Embedded Resource".

Apply "build action" in Visual Studio:

Select the XAML file -> Properties -> Build Action = Embedded Resource


This happened to me because a Nuget package uninstaller blew away all the attributes on the <Application> element in App.xaml. This included the x:Class attribute, which specifies the application class name. So the partial class containing the InitializeComponent() method was never generated.

I fixed the problem by reverting App.xaml to the source-controlled copy.


I had the same problem, but in my case none of this helped. In my situation every WPF project I had (including newly made projects) stopped compiling with this error. Eventually I uninstalled all the .Net frameworks then reinstalled them and things started working again. I also did a reinstall of Visual Studio, but it turned out that had no affect.


I've encountered this a couple times and keep forgetting what causes it. I ran into this when I renamed the namespace on my code behind file but not in my XAML.

So check if you've done the same.

The namespace and class names need to match since they are both part of a partial class

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

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

this happened with me when I accidentaly deleted the class reference from the xaml definition:

I've replaced the

<Window x:Class="myapp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

first line with this:

<RibbonWindow 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

I know this isn't the answer to the original question (because thats project builds on another machine), but the error message was the same, so maybe I'll help someone with this situation.


You might get this error when you import a class from another project, or change the path of the xaml file, or the namespace of either the xaml or behind .cs file.

One: It might have a namespace that is not the same as what you have in you new project

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

As you can see the name space in the imported file begins with the old project name: "TrainerB", but your new project might have a different name, so just change it to the correct new project name, in both the .xaml file and the behind .cs file.

Two:

change the properties of the .xaml file to:

Build Action: Embedded Resource

Custom Tool: MSBuild:UpdateDesignTimeXaml

Xaml file properties

Xaml Namespace Correcting 01

Xaml Namespace Correcting 02


The best shot at an MCVE in this thread is, with VS2017 15.5.2, load up the XAML of LabelControlAdvancedSample, the last example in this tutorial page.

<Window x:Class="WpfTutorialSamples.Basic_controls.LabelControlAdvancedSample"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="LabelControlAdvancedSample" Height="180" Width="250">
<StackPanel Margin="10">
    <Label Target="{Binding ElementName=txtName}">
        <StackPanel Orientation="Horizontal">
            <Image Source="http://cdn1.iconfinder.com/data/icons/fatcow/16/bullet_green.png" />
            <AccessText Text="_Name:" />
        </StackPanel>
    </Label>
    <TextBox Name="txtName" />
    <Label Target="{Binding ElementName=txtMail}">
        <StackPanel Orientation="Horizontal">
            <Image Source="http://cdn1.iconfinder.com/data/icons/fatcow/16/bullet_blue.png" />
            <AccessText Text="_Mail:" />
        </StackPanel>
    </Label>
    <TextBox Name="txtMail" />
</StackPanel>

Having left the App.xaml & App.xaml.cs at default, attempting to compile the above produces the linker error.
Fortunately, when hovering over the InitializeComponent() statement in LabelControlAdvancedSample.xaml.cs there is a linked text hint:

Show potential fixes.

Clicking it invokes another linked text:

Generate method MainWindow.InitializeComponent.

Doing this produces the following "do nothing" method:

    private void InitializeComponent()
    {
        throw new NotImplementedException();
    }

The function must be defined for the project to build. Looks like something differs in the implementation of InitializeComponent in WPF to VB.Net.
Edit: The namespace.class in the first line of the xaml is not correct. According to MSDN and @Sean B's answer, it should be

<Window x:Class="LabelControlAdvancedSample.MainWindow"

Thus the project compiles without error and the dummy InitializeComponent method is not required, in fact it generates more errors. Goes to show VS can be helpful, even in the extremely rare case of user error. :P


  1. Navigate to the solution directory
  2. Delete the \obj folder
  3. Rebuild the solution

I encountered this error during refactoring where I renamed some files/folders and the prexisiting *.g.cs files needed to be re-generated.


For those who have no errors in Debug mode, but do have the specified error in Release mode (and yet the project runs fine), here is something simple to try:

  1. Open the XAML file corresponding to the offending xaml.cs file.
  2. Make an edit--any edit, like add a space somewhere
  3. Save the file and close it

This method worked for me in VS 2015, and according to other users, also 2017 and 2019


I've had this (although it was very much my fault and was caused after I copied and pasted some code in); it can occur when the namespace doesn't match between the XAML and code behind

EG

<UserControl x:Class="DockPanel.TreeView" />

and the code behind is

namespace NotDockPanel

After some action the namespace of the .cs file and the one in .xaml file may be different (in xaml look for the x:Class="namespace.yourType").

Fix them to be the same.


So I realize this is an older question, but we were having a similar issue. We were able to build a project using VS2012, but not using msbuild from the command line. I went into the .proj file and noticed it didn't have a record for "ProjectTypeGuids" under the default "PropertyGroup" section, so I added this:

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

which is the project GUID for WPF. I then deleted and re-added the UserControl and it started working. I'm not sure if I had to do that last step, but it works for me now.


Since this seems to be the go-to thread for the problem regarding missing 'InitializeComponent', I'll include my answer here.

I too was having this issue and I've tried everything I found here and in all other Forums that Google could find, however none resolved the issue for me. After two hours of trying everything, I finally figured out what was wrong with my setup.

In our project, we are using Metro components from MahApps. The view that was giving me trouble was a view inheriting from MetroWindow, like this:

<Controls:MetroWindow x:Class="ProjectNamespace.MyView"
                      xmlns:Controls="http://metro.mahapps.com/winfx/xaml/controls"
                      ... >

Now, I have defined my static resources as

<Controls:MetroWindow.Resources>
    <prop:Resources x:Key="LocalizedStrings"/>
    ...
</Controls:MetroWindow.Resources>

That's how I've defined Resources in UserControls in all my other views, so that's what I assumed will work.

That was, however, not the case with Controls:MetroWindow! There I absolutely needed the resource definition as follows:

<Controls:MetroWindow.Resources>
    <ResourceDictionary>
        <prop:Resources x:Key="LocalizedStrings"/>
        ...
    </ResourceDictionary>
</Controls:MetroWindow.Resources>

So my issue, in summary, was a missing <ResourceDictionary> tag. I really don't know why this produced the 'InitializeComponent' error and it weirdly didn't even produce it on every machine of mine, but that's how I fixed it. Hope this helps (the remaining 0.001% of people encountering this issue).


Another possible explanation is that you're building against x86. Right-click your Solution and choose Configuration Manager. See if you're building against x86 instead of Any CPU.


The issue appeared while I did not change the code, using a recent VS2019 16.7.5.

Just opening for edition the corresponding XAML file solved the problem.


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.


The Build Action for the .xaml file must also be set to "Page", when moving a xaml file between projects this setting gets lost (in VS 2010 at least).


I had the same problem, expect I coped my MainWindow xaml and cs into a new file and then copied them back to their original place. I then got this error after trying to compile the WPF app.

What I did to fix this error was rename the namespace (from egNamespace -> egNamespaceNew, and it worked again. I then changed the namespace back to the original one.


I encountered this while renaming a usercontrol. The way I fixed it was to comment out InitializeComponent, verify that all the names were correct (xaml and code behind), build the project, uncomment InitializeComponent, then build again. It sounds like there may be a couple causes/solutions for this issue, but this way did it for me.


I just encountered this problem, and it turned out to be that my project is stored in my user folder, which is stored on the network, and we had a momentary network outage. I did a build; it complained that my files had been modified outside the editor (they hadn't; the file locks just got borked), and it built fine, removing the error regarding the InitializeComponent() method.

BTW, in case you're wondering, developing something from a network drive is bad practice. It becomes particularly problematic when you're trying to leverage .NET's managed code; in my experience, it freaks out every time you build. I forgot to put this little throw-away project in the proper folder, and ended up paying the price.


In my case there's been a reference inside my project which was wrong but that wasn't reported.

I solved my problem with readding all my references even if they were meant as correct.


There's a very specific reason for this, and it's in the project settings. This usually happens whenever you try to add a WPF control/window to a .NET 2.0 class library or project. The reason for this error is that the project does not know it's building a WPF control or window and therefore tries to build it as a C# 2.0 project.

The solution involves editing the .csproj file. Right click on the project causing the problem and select “Unload Project”. Right click the unloaded project and select “Edit .csproj”. The .csproj file will open and you can see the XML. look for the following line:

<Import Project=…..

It's near the end of the file, and the only line that you have is probably

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />

This tells Visual Studio to build the project as a .NET 2.0 project. What we want to do is to tell Visual Studio that this is actually a WPF project, so we have to add the following line:

<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />

This line will tell Visual Studio to build the project as a WPF project. Now your .csproj file bottom should look like this:

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />

Save the .csproj file, right click it in Solution Explorer and select “Reload Project” compile and that's it, you're all done!


Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to visual-studio-2010

variable is not declared it may be inaccessible due to its protection level SSIS Excel Connection Manager failed to Connect to the Source This project references NuGet package(s) that are missing on this computer Gridview get Checkbox.Checked value error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop? Attach (open) mdf file database with SQL Server Management Studio What is and how to fix System.TypeInitializationException error? Could not load file or assembly "Oracle.DataAccess" or one of its dependencies IIS error, Unable to start debugging on the webserver

Examples related to visual-studio

VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio? How to download Visual Studio Community Edition 2015 (not 2017) Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio Code pylint: Unable to import 'protorpc' Open the terminal in visual studio? Is Visual Studio Community a 30 day trial? How can I run NUnit tests in Visual Studio 2017? Visual Studio 2017: Display method references

Examples related to initializecomponent

The name 'InitializeComponent' does not exist in the current context