C# / WPF: InitializeComponent does not exist in the current context

A problem that has cost me a good few hours in Visual Studio when programming a WPF application with C# is that the method InitializeComponent() in the structure of the CodeBehind of the MainWindows or in other dialogues has brought an error message.

Error with InitialiseComponent()

This is the following error message:

CS0103: The name ‘InitializeComponent’ does not exist in the current context

Screenshot of the error message that the name InitializeComponent does not exist in the current context.
Error/Warning CS0103 for InitializeComponent

Despite this error message, the application was compilable, but showed strange behavior. Among other things, newly inserted UserControls in the CodeBehind were no longer recognized during programming.

If you search the Internet, you will come across many forum posts stating that this error has already cost other programmers many hours and even caused them to despair.


You can also read that there can be several different causes for the problem. One reason could be that the namespace in the CodeBehind does not match the namespace included in the XAML file. They must therefore be the same:


CodeBehind: namespace MyNamespace{}

XAML: x:Class=”MyNamespace.MainWindow”

I was able to rule that out in my case.

Another way to try it out is to delete the obj folder in the solution and close and restart Visual Studio once. Then do a rebuild of the solution. But even that didn’t help in my case.

In my case, the problem was apparently in the build settings for the XAML file. The custom tool had “MSBuild:Compile” in it.

Screenshot of the page properties of the XAML file before fixing the error
Page properties of the XAML file with error message

I have set the property “Copy to Output Directory” to “Do not copy” and as Custom Tool I have entered the XamlIntelliSenseFileGenerator .

Screenshot of the page properties of the XAML file without the error message for InitializeComponent
Page properties of the XAML file without error message

In a more or less magical way, it works and the above-mentioned error message for InitializeComponent disappears. I don’t really have a reliable explanation for this. But I think that MSBuild is possibly not really suitable for compiling XAML files or cannot distinguish properly between WindowsForms and XAML files. It is therefore better to use a XAML compiler directly.

Leave a Reply

Your email address will not be published. Required fields are marked *