The name 'InitializeComponent' does not exist in the current context
Asked Answered
P

54

511

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?

Pentyl answered 3/8, 2011 at 11:15 Comment(7)
This user "error" looks like easy to solve, just a simple x:Class proper definition. Until there all is ok, developer should pay more attention, but what if is not this error but a ghost error with the same error message? I read A LOT of different voodoo workarounds from 2012. It would help from VS a much clear error message and OF COURSE a bugfix for the ghost errors with the same message. Developers are since 2012 changing the build config from files, projects, copy-pasting the project, deleting files from App folder, restarting VS, etc. Bravo MS... a 4 years bug and still getting older!Jaynejaynell
For any future readers of this question: This problem seems to have a lot of possible sources. In my case the first few answers did not help, but one of the answers further down was correct.Sniffy
@Sniffy Namespace of the Designer file was the issue for me.Sheffie
While this can be caused by many things (Namespace renamed \ Page type - MSBuild), i have eventually found the solution for what was causing it on the project I inherited. In the .csproj files, i had to change the "ToolsVersion" from 4 to 15 (VS 2017).Appointee
Wow, this is still happening in Visual Studio 2022. I'm seeing it in a file that I can verify has NOT changed. I added an answer that worked for me today.Bender
For what it's worth, I clicked the "debug" option and it ran without issues. I also opened the project in VS 2022 (as opposed to 2019) and that worked without problems. no ideaEquanimous
Had this issue with a WPF app - it turned out that when I have deleted a class from the project, VS did not remove its references from the csproj file. I unloaded the project, manually deleted the redundant references and then reloaded it. Although it did not seem apparent that issue related to the "InitialiseComponent does not exist ..." error on a completely unrelated class, removing the non existent entries in the csproj file did seem to resolve itDistortion
B
919

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">
Bunnell answered 11/10, 2011 at 17:28 Comment(11)
Thank you Sean. I came here to post this answer here but you already beat me to it. This is exactly what had happened and it solved my problem. Your comment should be higher up the charts because it would have saved me 15 minutes.Alvardo
If the class names aren't the same you'll get the same errorQuadrivial
This is the answer. Not sure why it hasn't been chosen, but this is it and I ran into this coding some Xamarin.Forms.Sunglasses
I was wondering about where this is coming from. I didn't notice until now that Visual Studio is actually adding that x:Class attribute when you create the view. In my case, the class attribute had been removed in which case the generated code ended up in the correct class but in the global namespace.Misapprehend
When refactoring, make sure to include comments and strings (Visual Studio 2015)Acetamide
Yep. I had the wrong class name at the end of my <Window x:Class=""> attribute.Ningsia
For me (in Xamarain.Forms) using a "Quick Start" project downloaded from Azure, it was the white space / indent between xmlns:x="schemas.microsoft.com/winfx/2009/xaml" and x:Class that was the problem. I deleted this and retyped it and it worked!Lemke
I did the same thing. Renamed the solution, but the change didn't reflect in the Main window. Thank you Sean.Priorate
Initially this didn't solve it, but after I unloaded and reloaded the project, the error disappeared.Ardin
Also, don't forget about case sensitivityPaviour
I fixed by changing the import from <Import Project="..\packages\Xamarin.Forms.**** \build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets" Condition="Exists('..\packages\Xamarin.Forms.***** \build\portable-win+net45+wp80+win81+wpa81+MonoAndroid10+MonoTouch10+Xamarin.iOS10\Xamarin.Forms.targets')" /> to <Import Project="..\packages\Xamarin.Forms.****\build\portable-win+net45+wp80+win81+wpa81\Xamarin.Forms.targets" Condition="Exists('..\packages\Xamarin.Forms.****\build\portable-win+net45+wp80+win81+wpa81\Xamarin.Forms.targets')" /> in .csprojTacitus
O
292

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

Outtalk answered 17/11, 2011 at 16:16 Comment(14)
After a copy paste it happens that the xaml build action change from page to ContentGonick
Still happens in Visual Studio 2012 (Update 2)Allegory
Still happens in Visual Studio 2013Danelledanete
Worked for me on VS 2010! and I was using in a Xamarin Project...Taps
Also happens when moving a window inside the same project. Dragged it into a subfolder and build action was reset.Jeanene
Still happens in Visual Studio 2015 Community editionBeadruby
This also fixed IntelliSense in the XAML file :-oBarmecidal
Faced the same issue after one of updates in VS 2019! The build action was set to Page. Solved it by chaning the build action to some other value and back to Page again.Canula
This still happens in Visual Studio 2019 v16.3 in WPF .NET CORE 3.0 if you got custom controls (xaml + cs) defined in an external library.Fibroid
The Build Action WAS set to page for my case, BUT switching it to none and back to Page worked!Dalury
Simply changing the Build Action from "Page" to anything... and then back to "Page" fixed it for me!Antinomian
In case of Avalonia UI the Build Action is "Avalonia XAML" and in my case it was not in the list so I edited the .projitems manually -- switching from Compile tag to AvaloniaXAML and it works.Lettering
Excellent! This was the answer for me along with Caleb W. comment.Organography
It's 2024 and Visual Studio 2022 latest update... yet we still getting this problem, and yeah, changing it to something else, then back to Page fixed it.Aponeurosis
D
173

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, 2019 and 2022

Doriedorin answered 14/10, 2015 at 16:14 Comment(18)
Crazily enough, this worked for me with VS2015. And it fixed all of the errors in all the XAML files. This is a really WTF moment.Vandalism
Same in VS2017 and this fixed it.Greenback
I was getting conflicting errors after copying a view and renaming it (references were going to old view name in some places still). I tried deleting the "obj" folder but then got what OP mentioned. Doing this method fixed that though!Reject
WTH with Visual Studio !!! This trick solved my problem in VS 2017. I was scratching my head with frustration. Thanks a lot :)Buttery
Upgraded the project from VS2013 to VS2017, and had a handful of XAML/.cs files with this complaint, your tip just saved me from ripping the remains of my hair out. Thanks!Farquhar
Works On Visual Studio 2017 with Resharper. Can't believe they still haven't fixed itAlienage
@WilliamDenman Yup, there are a bunch of these bugs in VS at this moment. y2u.be/ld2nWfIap2kAswarm
@PhilipVaughn Same issue using Rider.Wavawave
Would be interesting to know, whether everybody is using ReSharper of some sort (either VS or Rider).Wavawave
@Wavawave I've never used any of thoseDoriedorin
@Doriedorin Okay, so it should not be ReSharper/Rider related.Wavawave
For me, any change didn't help - I had to change the x:Class value to something broken and then back again. Apparently this forces VS to rebuild its partial class cache or whatever... Very annoying, indeed!Revanche
@Doriedorin just wanna say F_U :) why didn't you tell this sooner so it could be marked as an accepted solution cause this is the only way that works for me!Reliquiae
Also works on VS 2022 + .NET 6. In my case the error was only shown in the debug mode. This method helped. Thanks.Undertake
With Microsoft Visual Studio Professional 2022 Version 17.5.4 this error happened after using the built-in merge conflict editor, and accepting merge in the xaml file. Making a dummy edit in xaml did clear the error.Takashi
how do I bounty this answer? works for Visual Studio 2022 version 17.6.2 omgPrimogenial
i came back to this answer 1 month later and still worked. what a charmPrimogenial
Unbelievable, worked for me in VS2022 after moving Page files WinUI3. It did fail in debug mode before your fix.Darsie
M
106
  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 pre-existing *.g.cs files needed to be regenerated.

Magistery answered 5/4, 2013 at 20:2 Comment(7)
Seems like i have the same problem, but this didn't work for me.Vento
Do this after checking your xaml x:Class matches the Namespace.Class.Jany
This works. In Visual Studio Code, have to restart OmniSharp as well in order to force the re-build.Otocyst
I went to the less drastic approach: I searched for the corresponding g.i.cs file, renamed it and re-compiled. That file got regenerated and everything worked fine. In case this would not have been the case, I would have been able to rename it back as before, which you can't if you delete it :-)Zeitgeist
This worked for me! Thank you so much! I have to remember this! It happens enough that I have to figure it out, but not often enough that I can remember it. DOH! Thank you.Invaginate
It works in my project using VS 2022 + .NET 8. Thank you!Nudge
Literally the only good fix. Thank you! Works on Visual Studio 2022 17.9.3Bimestrial
P
33

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!

Puggree answered 3/8, 2011 at 11:20 Comment(5)
I tried this before I wrote this question and it doesn't help. I think it's a bit weird that I can't compile new project but my colleague can...Pentyl
I tried it too and it didn't help. Adding the new import resulted in a new warning (see below) but the original error is still there."C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.WinFX.targets" cannot be imported again. It was already imported at "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.NETFramework.targets (76,3)". This is most likely a build authoring error. This subsequent import will be ignored. "Coquina
Thank you, this fixed it for me, on a project i inherited.Appointee
Worked for me! The only difference (maybe due to VS 2019) was that MSBuildToolsPath was used instead of MsBuildBinPath for the reference to Microsoft.CSharp.targets. But the code I needed to insert was just as specified in the answer. Wonderful!Revanche
It's so frustrating that Visual Studio somehow forgot what kind of project i'm working on - i wonder why this happens ? Thanks anyway, it fixed it for me !Hymenopteran
I
28

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.
Incorrupt answered 14/9, 2016 at 21:55 Comment(3)
This one worked for me. I had made a copy & paste and rename of a usercontrol I had, when the InitializeComponent() started failing.Womenfolk
How on earth did you stumble across this fix? I tried everything else and this worked. Using VS 2017, so problem is current.Indelicacy
This also worked for me in VS 2022.Horsehide
U
23

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.

Unsavory answered 16/3, 2014 at 14:16 Comment(2)
this wasn't exactly my problem but it helped me localize it. I had the namespace without the class name afterwardsOribella
This helped me find my issue, in my case I was missing the x:Class line, adding this in fixed it for meInoculate
D
19

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

Dialectology answered 15/5, 2016 at 22:7 Comment(1)
Omg! really thank you for that solution. I tested every solution found there and nothing work. The trick was in the properties of the xaml file. +1Withy
S
19

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.

Sheffie answered 22/11, 2018 at 15:42 Comment(1)
I had also problems with namespaces then adding new items to project. Problem was that I used spaces in project's name then I created it.Joejoeann
B
18

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
Base answered 29/8, 2013 at 11:29 Comment(1)
This led me to discover that my Designer had an incorrect namespace. Thanks!Sheffie
R
13

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.

Relations answered 15/2, 2012 at 15:57 Comment(1)
I didn't rename anything? However this solution worked for me. The *.g.cs and *.g.i.cs were missing in the obj folder, commenting it out and building the project generated the missing files. Not sure how it got into this state.Toombs
P
11

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!

Pameliapamelina answered 15/4, 2016 at 17:6 Comment(3)
I would have added this as a comment to the correct answer, but I don't have the rep to do so :(Pameliapamelina
Thanks for this! Worked for me after going crazy trying all sorts of things. My solution did build originally with no errors, then after PC was asleep for a while tried again and was getting the error. Maybe something to do with sleep mode?Irrefrangible
I had the same issue and solution. I believe it had something to do with IntelliSense. Changing the namespace in the xaml probably triggered an update of the relevant parts in the IntelliSense db. This is only a guess though.Judd
D
11

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

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
Dissimilate answered 19/2, 2020 at 17:37 Comment(2)
I found that this did the job for me, in a multi-targeting project, with target frameworks net47;net5.0-windows.Pettaway
This worked for me in a multi-targeting WPF user control library targeting net48, net5.0-windows, and net6.0-windows. The only context to have this problem net6.0-windows, and changing Sdk to Microsoft.NET.Sdk.WindowsDesktop fixed it. I then changed it back to Microsoft.NET.Sdk, and the problem remained fixed. I am so over the instability of every modern version of Visual Studio. Each new version seems to bring new features and new instabilities, with only a small portion of the old problems fixed.Riverside
C
10

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

Crandell answered 2/6, 2017 at 14:39 Comment(0)
A
9

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.

Abampere answered 3/4, 2017 at 2:22 Comment(1)
Thanks. I needed someone to say this.Patent
A
8

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

Alecalecia answered 2/8, 2017 at 8:49 Comment(1)
Hooray for you sir/madam!Rotund
S
7

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

Screwworm answered 17/9, 2015 at 8:37 Comment(4)
open and closing visual studio you mean?Vento
Some times, XDesProc.exe (Microsoft Visual Studio XAML UI Designer) will Stop the Visual Studio to work properly, and will not load the xaml file properly. So Restarting the Visual Studio solved my problem. (You can also go the Processes in the Task Manager, and stop only that process without Restarting Visual Studio).Screwworm
I discovered this in VS2017. I had changed everything else and the namespaces were correct everywhere but the InitializeComponent() calls had the error, and the partial keywords in the xaml.cs files had a warning, something like "partial class has only one file". I happened to close and reopen the solution and discovered both these issues resolved themselves.Brenda
@Vento Kind of, but in other order. First closing and then opening Visual Studio fixed the problem for me.Brougham
W
7

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.

Whiteeye answered 9/8, 2016 at 18:49 Comment(1)
If the error appears in all Xaml.cs files, then it has to be changed in every Xaml.cs files. Thank you for your comment, after 2 days this solved it. (:Tortuga
S
6

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

Servitor answered 9/8, 2013 at 13:56 Comment(0)
A
4

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.

Aquatint answered 4/2, 2012 at 3:24 Comment(1)
I got the same error due to a missing x:Class attribute, but it had nothing to do with Nuget. It just disappeared somehow, probably some visual studio magic.Johnathanjohnathon
B
4

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
}
Belldame answered 19/6, 2012 at 15:17 Comment(0)
K
4

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

"Startup object" (Not set)

Koeppel answered 18/3, 2016 at 17:31 Comment(3)
All other specifics mentioned in the question were the same?Keeley
Exact specifics are not exact considering the question was not clear on how the exception manifested. However the underlying symptom is identical therefore I don't see anything wrong with my answer. My intention was to add to the conversation as no answer/comment helped in my case. I was merely attempting to add to the knowledge base for the often times nondescript compile errors.Koeppel
Thanks! It solved my problem! It seems that the given option (Startup object) was reset automatically when I moved the MainWindow.xaml from root to View directory.Blueberry
T
4

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.

Theda answered 29/3, 2018 at 14:42 Comment(0)
D
3

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>
Driving answered 4/8, 2015 at 8:12 Comment(1)
In my csproj I was missing the <DependentUpon>YourFile.xaml</DependentUpon> for some reason and this is what fixed it for me!Flyman
B
3

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.

Banc answered 14/12, 2015 at 10:23 Comment(0)
N
3

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.

Nigeria answered 28/4, 2016 at 17:27 Comment(1)
Worked for me. Except I left App.xaml as Application definition. Working in WinUI3 Preview 5/Reunion 0.5.Bova
G
3

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

Gaspar answered 29/11, 2016 at 14:59 Comment(0)
P
3

Richt click on the file in the solution explorer and choose "Exclude From Project". After this make sure you have "Show All Files" in the solution explorer activated. Then include the xaml and the xaml.cs file again, rebuild the project and after this it should work again.

Princess answered 11/9, 2023 at 8:42 Comment(0)
D
2

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.

Diabolic answered 27/4, 2015 at 22:41 Comment(0)
M
2

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.

Magel answered 18/6, 2015 at 22:59 Comment(0)
C
2

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.

Corney answered 1/10, 2015 at 12:58 Comment(0)
E
2

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.

Ezechiel answered 5/1, 2016 at 20:49 Comment(0)
V
2

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.

Vento answered 13/1, 2016 at 9:42 Comment(0)
C
2

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

Capacitate answered 30/12, 2017 at 4:31 Comment(0)
M
2

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.

Milinda answered 16/11, 2018 at 17:32 Comment(0)
S
2

My way is close solution and delete ".vs" folder under the solution path.
(it will make you lost all of your editor status - list of opened files, window location, and error cache)

It always work.

Supposititious answered 13/10, 2021 at 8:53 Comment(2)
Did this and reopened the project. After building, the error returned. The csproj file had <UseWpf> in it and there were no <Page> entries.Postscript
@Postscript Bad comment, you didn't tell me what error you got. But you said that there has <UseWpf> in csproj, which means that you should working on a .NET Core + project . It will include the presumably valid project files into project from the project directory by default, and compile them by default way according to the file extension name. Xaml files will be processed as "Page" by default. So, there is no <Page> in the csproj is in normal situation.Supposititious
M
1

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.

Marcie answered 23/12, 2013 at 3:11 Comment(0)
E
1

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.

Economist answered 1/3, 2015 at 17:43 Comment(0)
I
1

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

Iand answered 20/11, 2018 at 8:45 Comment(0)
F
1

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.

Faradmeter answered 24/4, 2020 at 22:54 Comment(0)
S
1

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.

Skydive answered 10/7, 2020 at 22:23 Comment(0)
B
1

I had a problem similar to this in WPF. I had copied a usercontrol but had forgotten to rename the public ViewModel property in its.xaml.cs file for it. But still wasn't working. I eventually deleted all of the files inside the obj\debug type of folder for the project (we had this named differently). And rebuilt it. It still wasn't working, and I exited Visual Studio. (Before this I had at one point two instances of Visual Studio I think maybe.) The problem I had was that it was reporting it had this error when I had already fixed it! When I came back into Visual Studio (after deleting the debug stuff in obj), there finally was no error indicator. Then I rebuilt the project and now all was good!

This is not the exact order that I did things here. It needed to be simplified.

Bulldozer answered 23/7, 2021 at 22:22 Comment(0)
J
1

This happended to me when I tried to build an SDK Project targeting net48. It works fine with MSBuild.exe, but dotnet build fails with the given error.

What worked for me was

  1. Add <UseWPF>true</UseWPF> to the <PropertyGroup/> node
  2. remove all <Page /> elements, as they are included automatically now.

Now msbuild as well as dotnet build work.

Here is the complete project file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{07465991-AC74-4C22-B1DE-7BA67A040631}</ProjectGuid>
    <OutputType>library</OutputType>
    <RootNamespace>MyRootNamespace</RootNamespace>
    <AssemblyName>MyAssemblyName</AssemblyName>
    <FileAlignment>512</FileAlignment>
    <PackagesDirectory>$(UserProfile)\.nuget\packages</PackagesDirectory>
    <ResolveNuGetPackages>true</ResolveNuGetPackages>
    <SkipValidatePackageReferences>true</SkipValidatePackageReferences>
    <TargetFramework>net48</TargetFramework>
    <TargetFrameworkProfile />
    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
    <IsNetCoreProject>false</IsNetCoreProject>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">15.0</VisualStudioVersion>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
    <AutoGenerateBindingRedirect>true</AutoGenerateBindingRedirect>
    <ResolveAssemblyReferencesSilent>true</ResolveAssemblyReferencesSilent>
    <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
    <UseWPF>true</UseWPF>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>embedded</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>embedded</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Xml" />
    <Reference Include="Microsoft.CSharp" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="System.Net.Http" />
    <Reference Include="System.Xaml" />
    <Reference Include="WindowsBase" />
    <Reference Include="PresentationCore" />
    <Reference Include="PresentationFramework" />
  </ItemGroup>
</Project>
Jolee answered 22/6, 2022 at 14:11 Comment(0)
R
1

I was converting a solution from Xamarin to Maui.

I needed to change MyPage.xaml file Properties/Build Action

from "Embedded resource" (the way it was used in Xamarin)

to "MauiXaml" (as it is used in Maui).

I also had to clear Properties/Custom Tool.

Roots answered 28/12, 2022 at 15:26 Comment(1)
This also happens when you add a view as a new item from VS2022. It sets it to embedded resource.Lewanna
D
1

This issue happened to me after I moved my Views and ViewModels to a different project in VS2022. I was careful to ensure I renamed the namespaces correctly but the issue still persisted. What I did to correct the issue was to go into the Solution Explorer and rename each View to a different name then go back to Solution Explorer and rename each View back to their original names and all the errors went away.

Dvina answered 14/11, 2023 at 1:11 Comment(0)
D
0

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.

Dexterdexterity answered 10/4, 2013 at 16:49 Comment(0)
S
0

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.

Sayres answered 5/7, 2013 at 12:48 Comment(1)
OMG after all that no bueno? I am in agony!? All I did was switch branches in order to merge, and it has all turned upside down. any advice?Equanimous
A
0

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

Allurement answered 25/6, 2014 at 17:54 Comment(0)
T
0

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.

Taler answered 23/8, 2020 at 10:21 Comment(0)
S
0

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.

Schizomycete answered 11/10, 2020 at 15:12 Comment(0)
B
0

(Old question but if searching brings you here)

01/09/2022 - experienced the problem in visual studio community 2022.

The issue was being reported for a .xaml.cs file that had NOT changed.

The solution that worked for me today:

copied the last xaml file that I had been working on (and xaml.cs) to a folder not in the project tree.

Right click on the file in solution explorer and select 'Delete' (this removes the files)

Rebuild the project (it will have errors where it references to the file)

Copy the xaml and xaml.cs files back to the project folder

Right click on project and select 'Add/Existing Item' and pick the xaml file. Rebuild the project

(for me it build and the errors on the other xaml file had gone)

Bender answered 1/9, 2022 at 12:2 Comment(0)
E
0

I ran into this issue when migrating .net461 projects to the new SDK-style csproj format using the migration wizard. I had to add this to my csproj:

  <PropertyGroup>
    <UseWPF>true</UseWPF>

And then remove any Page tags that were generated from the migration wizard...

<Page Include="Views\MyCustomControl.xaml">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
</Page>
Equivalence answered 9/9, 2022 at 17:57 Comment(0)
J
0

Had this issue when setting Build Action to Application Definition on App.xaml on a project with an OutputType of Library. Visual Studio only gave a "clearer" warning of Error MC1002 Library project file cannot specify ApplicationDefinition element on build.

Jacquard answered 5/3 at 9:28 Comment(0)
U
-4
OK     this.InitializeComponent(); 

Wrong  this.InitializeComponent;
Unsatisfactory answered 15/2, 2022 at 20:33 Comment(1)
Please read "How to Answer" and "Explaining entirely code-based answers". It helps more if you supply an explanation why this is the preferred solution and explain how it works. We want to educate, not just provide code.Avoirdupois

© 2022 - 2024 — McMap. All rights reserved.