New .Net MAUI App project throws 'The name 'InitializeComponent' does not exist in the current context' build errors
Asked Answered
T

20

54

I've attempted to start playing with .Net MAUI and I've setup my development environment following the steps as described in:

  1. https://learn.microsoft.com/en-us/dotnet/maui/get-started/first-app?pivots=windows
  2. https://learn.microsoft.com/en-us/windows/apps/project-reunion/set-up-your-development-environment#required-workloads-and-components
  3. https://learn.microsoft.com/en-us/xamarin/android/get-started/installation/android-emulator/device-manager?tabs=windows&pivots=windows

I've also run the 'maui-check' CLI tool and everything checks out, but when I create a new .NET MAUI App with Visual Studio 2019 v16.11.0 Preview 2.0 (running on Windows 10 Home 20H2), I get the 'The name 'InitializeComponent' does not exist in the current context' build errors. It also doesn't find the references to any controls on the form e.g. 'The name 'CounterLabel' does not exist in the current context'

I've tried almost everything in this post The name 'InitializeComponent' does not exist in the current context which contains suggestions like adding and removing files, making changes and changing them back... basically everything except throwing a penny in a wishing well.

I found that a common mistake is a namespace mismatch, but here is what I have showing that the namespaces are correct:

App.xaml:

<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MauiApp1"
             x:Class="MauiApp1.App">
    ...
</Application>

App.xaml.cs

using Microsoft.Maui;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.PlatformConfiguration.WindowsSpecific;
using System;
using Application = Microsoft.Maui.Controls.Application;

namespace MauiApp1
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent(); <-- This is throwing the build error...
        }

        protected override IWindow CreateWindow(IActivationState activationState)
        {
            this.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>()
                .SetImageDirectory("Assets");

            return new Microsoft.Maui.Controls.Window(new MainPage());
        }
    }
}

MainPage.xaml:

ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp1.MainPage"
             BackgroundColor="{DynamicResource PageBackgroundColor}">

            ...
</ContentPage>

MainPage.xaml.cs

using System;
using Microsoft.Maui.Controls;

namespace MauiApp1
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent(); <-- This is throwing the build error...
        }

        int count = 0;
        private void OnCounterClicked(object sender, EventArgs e)
        {
            count++;
            CounterLabel.Text = $"Current count: {count}"; <-- This is throwing the build error...
        }
    }
}

Any help will be greatly appreciated!

---=== UPDATE ===---

The path to the project I created is c:\develop\c#...... as soon as I copy the project to a folder that doesn't contain 'c#' it works. This clearly causes some parsing in the background to fail.

Tiruchirapalli answered 19/6, 2021 at 12:48 Comment(1)
M
65

I faced the same issue and looks like when I created a ContentPage in VS its still pointing to Xamarin Forms. After changing namespace to MAUI, I updated the Build Action(RightClick on Xaml Page>>Properties>>BuildAction) of XAML Page to MauiXaml and it worked for me.

Multilateral answered 4/7, 2021 at 16:8 Comment(3)
Also make sure to remove anything listed for 'Custom Tool and Custom Tool Namespace'B
Edit queue is full for this answer, but take in consideration that now it's possible to add a new ContentPage for MAUI within the Add > New Item Menu. Just select under Visual C# Items > .NET MAUI > .NET MAUI ContentPage (XAML). That will also geerate the C# file with template applied.Anticipate
Here I am 2 years+ later and I still have this problem. This answer worked like a charm.Lothair
L
42
  1. Close VS2022
  2. Open VS2022
  3. Open project with menu VS2022(File - Open - Project...)
Llovera answered 20/10, 2021 at 14:0 Comment(6)
This turn off/turn on approach did work for me too - but I just closed and opened the solution without closing VS2022. Someone downvoted you, probably because you didn't explain your answer more fully. Personally, I don't know why it worked either.Mcfadden
Restarting VS22 worked for me. Thanks! Still a problem 4 months later.Dragster
closing visual studio and taking the project work for me visual studio 2022 17.1 preview.Seaboard
Worked for me too closing and opening the entire Visual studio 2022. This should be the accepted answer.Duplicate
Using VS 2022 Preview 17.1.0 Preview 3.0, and this worked for me too.Kingofarms
Worked for me on macOSMyalgia
E
11

The same error popped in for me being an absolute beginner and missing the ending '>' in the XAML file. So, It could also be XAML errors, which leads to this error.

Eustoliaeutectic answered 18/6, 2022 at 8:56 Comment(3)
LOL. This one hurts -- but that was my problem.Torsk
I had the same thing happen. I think mine was an issue with the xaml "ContentPage" values.Kirstiekirstin
Same solution for me -- I'm in Visual Studio Code with whatever recommended C# and Dotnet and Maui recommended plugins from the official Quick Start, but xml/code tags are not auto-closing. Silly me -- thanks for sharing this perfect tip!Aubree
H
10

What caused it for me was that I had renamed the xaml and xaml.cs file something else but I hadn't updated it in the ContentPage node in the xaml under x:Class

Hosbein answered 9/8, 2022 at 17:8 Comment(1)
If you move your page from "/" into a "/View" folder, this is the answer you need.Bellwort
S
7

Make sure you select a .Net MAUI Content Page and not a Content Page

Maui ContentPage

Sassy answered 28/2, 2023 at 17:55 Comment(0)
I
4

When copying in XAML make sure the x:Class refers to the correct namespace - I had errors when this class referred to the Notes namespace (e.g. Notes.AboutPage), whereas my project referred to the Calendar namespace (e.g. Calendar.App)

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Calendar.AboutPage"> <!-- Update the class namespace here -->
<VerticalStackLayout Spacing="10" Margin="10">
</ContentPage>
Inhaler answered 19/2, 2024 at 7:0 Comment(0)
S
3

I'm using VS 2022 Preview 17.4.0 Preview 1.0, I don't know why but when you create a new Content Page it creates with the wrong namespace. take a look in the C# file and fix the namespace. It worked for me.

Sympathizer answered 14/8, 2022 at 6:2 Comment(1)
Thanks! I'm using the preview also. When I added a new .NET MAUI ContentView (XAML) in the Views folder and it added the ".Views" to the end of the namespace, even tho all the other files in the Views folder don't have ".Views". I removed it and it works now!Teeter
L
3

Just run visual studio with "run as administrator" and everything is done

Lantana answered 3/5, 2023 at 10:7 Comment(0)
T
2

The path to the project I created is c:\develop\c#...... as soon as I copy the project to a folder that doesn't contain 'c#' it works. This clearly causes some parsing in the background to fail.

Tiruchirapalli answered 20/6, 2021 at 1:12 Comment(0)
C
1

I am using preview version of 17.5 VS2022, I add to do below changes to run the app after adding new page.

*.Xmal Build Action -> BundleResource

*.Xmal.cs Build Action -> Compile

My VS Version

New MAUI XAML Page

Xmal Build -> BundleResource

Xmal.cs Build -> Compile

Cuttle answered 18/11, 2022 at 5:44 Comment(0)
N
1

Incredibly, the correct answer for me is not on this page. I had to find+replace all in my solution:

find:

xmlns="http://xamarin.com/schemas/2014/forms"

replace with:

xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
Nobe answered 23/2, 2024 at 9:21 Comment(0)
M
1

I had this Issue when i move MainPage.xaml(.cs) into View/MainPage.xaml(.cs).

I had the Compile Error as mentionned in the question. I solved it by simply restarting vs2022.

Murmur answered 12/3, 2024 at 21:36 Comment(0)
S
0

A very simple answer but has happened to me a few times.

Make sure you are using the preview version of VS 2022. It is very easy to accidently open up any other version of VS, which will cause the error to occur.

Soberminded answered 16/1, 2022 at 23:4 Comment(6)
It happens with VS 2022 preview too.Flyover
Not sure why you downvoted it since you either didn't open it in preview, or your error is just a different one. Create a new project in MAUI, then open it up in VS 2022 standard, and you will see this error.Soberminded
I know I am in VS 2022 preview since it is the only version of VS I have installed... and I can clearly see the PRE icon on my taskbar.Flyover
if you only have 2022 preview installed then obviously this answer does not apply to you, so why are you even responding on it and wasting everybodies time.Soberminded
Because it's not useful. The only version of VS you can even create a MAUI project in (currently) is VS 2022 preview.Flyover
Well, if you had more than 1 version of VS installed, you would have understood that the project opens in the release version of VS 2022 by default giving you this error. Try reading answers that actually apply to your situation, you may get better results.Soberminded
G
0

I have found a workaround for this problem. I am a newbie to c# and especially to .net Maui therefore, my apologies if I misinterpreted things differently.

First things first The error is about the context that the InitializeComponent() resides in. Context is nothing but the nuget package dependency that the file is looking for.

To change the context

  1. Open the .cs file and at the top of the editor click the navigation bar as shown in the Image
  2. Change the context to Windows specific dependency from the list.

And also the other workaround would be to change the build action of the xaml file to MauiXaml as others mentioned

Gonzalogoo answered 23/5, 2022 at 13:25 Comment(0)
C
0

For me the problem was that I've probably accidentally pressed "Exclude From Project" on MauiProgram.cs file. Hence the error. Don't know how it could've happened. Probably clicked on the file when was deleting files that lies beside. I've spend some hours looking for the reason for this error. It was my first ever VS Code, C#/.NET MAUI project.

Just have been following the tutorial. Made all the input myself, never copypasted. And somewhere on the Step 4 it stopped working. So I've thought that maybe I made a typo somewhere.

Downloaded the final code from the tutorial and started comparing files. After sometime, I've noticed the difference in .csproj file. Bingo! The MainPage files supposed to be deleted, not just excluded from project. And MauiProgram.cs was excluded by mistake. At first I didn't even know how this lines got in the file. Than I've learned about "Exclude From Project". After including MauiProgram.cs back in the project it started working as expected.

    <ItemGroup>
      <Compile Remove="MainPage.xaml.cs" />
      <Compile Remove="MauiProgram.cs" />
    </ItemGroup>

    <ItemGroup>
      <MauiXaml Remove="MainPage.xaml" />
    </ItemGroup>

Tutorial

Cognoscenti answered 29/3, 2023 at 12:43 Comment(0)
H
0

Check if there are any errors in the xaml markup or any missing namespace reference in it. For me, I was migrating from Xamarin Forms to MAUI, some of the xml namespaces I was using were from Xamarin Forms such as extended properties from Xamarin Forms infinite scrolling Xamarin.Forms.Extended.InfiniteScrolling.

So, it was being used like this in a listview:

<ListView.Behaviors>
    <extended:InfiniteScrollBehavior IsLoadingMore="{Binding IsBusy}" x:Name="IsLoadingMore" />
</ListView.Behaviors>

Removing the reference and this line fixed the issue. Well, of-course I need to re-write this functionality.

Humfried answered 9/9, 2023 at 15:36 Comment(0)
R
0

And another rather rare case, i had

xmlns:draw="http://schemas.appomobi.com/drawnUi/2023/draw"

and that xmlns was defined in the same assembly that was failing to compile, with the error in question. So needed to change to

xmlns:draw="using:AppoMobi.Maui.DrawnUi.Draw"

and it went working.

Rennold answered 26/10, 2023 at 14:35 Comment(0)
P
0

Another issue could be: Make sure, your XAML has no errors

Pondweed answered 29/12, 2023 at 23:43 Comment(0)
B
0

Maybe this works for someone else.

None of this solutions worked for me, but i just move the folder to a different path and it worked. I dont why or how, but now it works

Busey answered 7/4, 2024 at 1:30 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewAllegorize
E
0

For me, both Microsoft.Maui.Controls and Microsoft.Maui.Controls.Compatibility were missing. I don't know why. Even creating a new Maui project. I've installed them and everything worked fine. Additionally, I had to enable "Allow NuGet to download missing packages" which was disabled.

Existentialism answered 27/6, 2024 at 17:22 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.