Search code examples
c#xamlxamarinxamarin.formscode-behind

The name 'InitializeComponent' doesn't exist in the current context


I know that this error has many answers, but they are all some system errors or smth like that. I just created this app and it worked fine. Then I added a view-model to handle my navigation between the register and login page and in login/register.xaml I updated the text to know on what page I'm. But now InitializeComponent is not recognized.

I put only Register page because login is the same but with login name:

using Xamarin.Forms;

namespace Appointments.Views
{
    public partial class RegisterPage : ContentPage
    {
        public RegisterPage()
        {
            InitializeComponent();
        }
    }
}

And the view-model:

using Appointments.Views;
using MvvmHelpers;
using MvvmHelpers.Commands;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Appointments.ViewModels
{
    public class RegLogViewModel : BaseViewModel
    {   
        public AsyncCommand GoToRegisterCommand;
        public AsyncCommand GoToLoginCommand;
        RegLogViewModel()
        {
            GoToLoginCommand = new AsyncCommand(GoToLogin);
            GoToRegisterCommand = new AsyncCommand(GoToRegister);
        }

        async Task GoToRegister()
        {
            await Shell.Current.GoToAsync($"//{ nameof(RegisterPage)}");
        }

        async Task GoToLogin()
        {
            await Shell.Current.GoToAsync($"//{ nameof(LoginPage)}");
        }   
    }
}

And Register.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Appoitments.Views.RegisterPage">
    
    <ContentPage.Content>
        <StackLayout>
            <Label 
                Text="Register Page!"
                BackgroundColor="Blue"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />

            <Button
                Text="Go To Login"
                Command="{Binding GoToLoginCommand}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Solution

  • There is a typo mistake in your Register.xaml, that results in different namespace between the xaml and the cs partial definition of your Register class.

    You have

    x:Class="Appoitments.Views.RegisterPage"
    

    instead of

    x:Class="Appointments.Views.RegisterPage"