Xamarin.Forms - InitializeComponent doesn't exist when creating a new page
Asked 07 September, 2021
Viewed 3K times
  • 60
Votes

I'm using Visual Studio to try out Xamarin.Forms. I'm trying to follow the guide: http://developer.xamarin.com/guides/cross-platform/xamarin-forms/xaml-for-xamarin-forms/getting_started_with_xaml/

In short, I create a Xamarin.Forms solution using a PCL and then try to add a Forms XAML Page to the PCL-project.

The code-behind that gets created looks like this:

    public partial class Page1 : ContentPage
    {
        public Page1()
        {
            InitializeComponent(); 
        }
    }

The problem here is that InitializeComponent(); is red. When I try to build I get informed that The name 'InitializeComponent' does not exist in the current context

I've been looking around for solutions and even though others have had the same trouble, their solutions wont work for me. Here is one suggestion i tried to use: http://blog.falafel.com/xamarin-error-initializecomponent-does-not-exist-in-the-current-context/

Please let me know if you have a solution for this problem. Thanks!

Update:

My PCL (which is where I also want to add my XAML-page) contains:

App.cs:

    public class App : Application
    {
        public App()
        {
            // The root page of your application
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {
                        new Label {
                            XAlign = TextAlignment.Center,
                            Text = "Welcome to Xamarin Forms!"
                        }
                    }
                }
            };
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }

And my XAML-page:

<?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="XamaTest.MyXamlPage">
    <Label Text="{Binding MainText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>

Code-behind:

    public partial class MyXamlPage : ContentPage
    {
        public MyXamlPage()
        {
            InitializeComponent();
        }
    }

30 Answer