74

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();
        }
    }
Brandon Minnick
  • 11,396
  • 12
  • 55
  • 108
user2915962
  • 2,547
  • 5
  • 28
  • 54
  • What version of the xamarin forms project do you have. I seem to remember an issue with the older project templates. – Steve Mitcham Mar 03 '15 at 07:01
  • I should mention that i use visual studio and a trial-version. How can check version or update to the latest? Thank you for answering. I tries to right-click on the pcl and download the latest xamarin-Forms from nuget. Same problem still. – user2915962 Mar 03 '15 at 07:21
  • Can you share your project's source code. – Artur Shamsutdinov Mar 03 '15 at 10:24
  • Thank you, I updated the question. Please let me know if you need more info. – user2915962 Mar 03 '15 at 13:21
  • Just in case of : I had the same issue after moving the solution to a new folder. I had to edit .csproj files to update the "packages" folder manually and then it happens to compile again. – bN_ Oct 31 '16 at 13:12

34 Answers34

60

UPDATE: This error doesn't usually appear in VS 2015, if it does, here's my original answer:

Found the solution! Right click on the .XAML file, select Properties.

You will see a Property called Custom Tool. Change its value from MSBuild:Compile to MSBuild:UpdateDesignTimeXaml

This will solve the problem. Dont know about the downvote, but here's my screenshot:

Screenshot UPDATE:

It reappears rarely. If it does, just open the Xaml and code behind files and save them. I know, its not the best solution, but it gets the job done.

Dushyant Bangal
  • 5,033
  • 4
  • 34
  • 69
  • Good to know. You can mark it "useful" for the next guy by giving +1 – Dushyant Bangal Feb 18 '16 at 06:24
  • Got the same on a clean new project from template. Changing and re-saving the code-behind and .xaml file fixed it for me. – angularsen Apr 29 '16 at 23:12
  • This was set in my case, but the error did appear still. – Simon K. May 12 '16 at 07:18
  • @SimonK. have you tried the re-saving trick? I haven't worked on Xamarin for a few months now, but looks like people are still facing this problem, and the trick is working for them too. – Dushyant Bangal May 12 '16 at 09:12
  • Project clean and rebuild did it for me. – Simon K. May 12 '16 at 10:01
  • Thought it was the solution actually I already had it implemented. I also tried the resaving trick and it did not work. – Ismapro May 18 '16 at 16:20
  • @Ismapro , clean and build might help. Its such a sad thing they haven't fixed this yet. – Dushyant Bangal May 19 '16 at 17:49
  • Getting it when trying to run [Xamarin's Developer Modal Pages sample](https://developer.xamarin.com/samples/xamarin-forms/Navigation/Modal/). Your solution does not work, the Custom Tool setting by the way is already set to what you mention. – Veverke Sep 27 '16 at 12:28
  • 3
    In my project, the value was MSBuild:UpdateDesignTimeXaml. After i change to MSBuild:Compile its fine. VS SUCKS – Bruno Brito Apr 26 '17 at 17:56
  • 2
    @Veverke, sorry for the late reply, but look at the bottom of my answer. If you already have `MSBuild:Compile` just open the Xaml and code behind files and save them. I know, its not the best solution, but it gets the job done. – Dushyant Bangal Apr 27 '17 at 09:35
  • 1
    Recently I had same issue, and this solution was not solving because of the very long path of my project files. I mean more then 160 chars 'til the class name. The .g.cs was unable to be generated. Changing the path ended the struggle. – Diego Rafael Souza Jun 07 '17 at 17:18
  • i had 1 error. now i have 2 errors after doing these steps. – cagri Nov 26 '18 at 06:28
37

I get this sometimes and here's the checklist that solved them so far:

  1. Make sure the namespace in .xaml and .xaml.cs match

  2. Inherit from the correct parent - ContentPage for a page and ContentView for a control

  3. Set build action of the .xaml file to Embedded Resource if in the shared project.

Gulzar
  • 10,451
  • 10
  • 52
  • 87
root
  • 2,288
  • 1
  • 22
  • 18
  • 1
    and for me - i needed 4. Property called Custom Tool. Change its value from MSBuild:Compile to MSBuild:UpdateDesignTimeXaml as said in another post here... – Tony Trembath-Drake Mar 01 '16 at 12:59
  • Setting the build action to EmbeddedResource fixed this for me. I copied the .xaml and .xaml.cs files over from a different project, and the .xaml didn't have a build action set. So thanks for your checklist. – Dalbergia Apr 19 '16 at 22:34
  • 2
    My problem was with x:Class. It seems it was still pointing at Page1 – frostymarvelous May 01 '16 at 13:42
  • 4
    Make sure the namespace in .xaml and .xaml.cs match.. This is an important point highlighed. Visual Studio sometimes do not autoupdate this. – Aman Sura Jun 16 '16 at 11:56
  • 1
    Fun fact: If you use the rename refactor on the class, the XAML is not updated, leading to this error. The IDE, as ever, is no help. – Cobus Kruger Mar 23 '18 at 10:23
  • 1
    yes, this is the major reason. Whenever we change namespace or class name of xaml.cs file, the associated xaml file is not updated. And this results in the mentioned error. – MrClan Aug 12 '18 at 12:21
  • "Lets auto generate code and have no link in the project for where it is or came from." What fu@!ing idition thought that this was a good idea. – Paul McCarthy Jul 18 '19 at 14:10
32

As far as my observation is concerned, in Visual Studio 2015, XAML properties are already set as suggested by highly-voted answers here by default, specifically :

  • Custom Tool = MSBuild:UpdateDesignTimeXaml
  • Build Action = Embedded Resource

but the error still appears sometimes... (like in this other question).

Editing the corresponding XAML file and then hit CTRL+S should work fine, but you don't have to. A cleaner way to force Custom Tools to be run is by right-clicking on the XAML file and then click on "Run Custom Tool" context menu.

enter image description here

Community
  • 1
  • 1
har07
  • 83,990
  • 12
  • 70
  • 116
12

Updating the Xamarin.Forms NuGet package should do the job

Brandon Minnick
  • 11,396
  • 12
  • 55
  • 108
Thomas Weller
  • 11,348
  • 3
  • 23
  • 34
  • Thank you for the tip. Unfortunatly it did not change anything in my case. – user2915962 Mar 03 '15 at 16:57
  • Hmm. I had the same problem and it worked for me. Are there any other packages in your solution? – Thomas Weller Mar 03 '15 at 17:03
  • No, just a "fresh" Xamarin.Forms app with the default PCL. – user2915962 Mar 03 '15 at 17:10
  • 2
    Found the solution here: http://blog.galasoft.ch/posts/2014/07/using-xamarin-forms-with-mvvmlight/ Appearatly there is a bug when you create a new xaml-page. It automatically gets the extension .cs instead of xaml. I never noticed this. Thank you! – user2915962 Mar 03 '15 at 17:18
  • 2
    @user2915962 The NuGet package update and clean/rebuild (+restarts) did not fix the problem for me. After reading you comment, I decided to add a new Xamarin Forms XAML page. The "InitializeComponent" error on both pages went away after a build with the new page! Looks like a VS state issue of some kind. When the problem was there I could step through the compiler generated InitializeComponent code without a problem. I'm guessing that adding a new XamForms XAML page after the NuGet package upgrade helped sort out some VS internal state that a clean/rebuild did not, but that is unconfirmed. – Richard Logwood Aug 23 '15 at 17:44
  • Worked for me, Thanks!! – vamyip Nov 07 '15 at 13:25
  • Actually updating the Xamarin.Forms is the main reason this bug happens. I don't know what they are doing but every stable release this bug comes back. Even after pre releases that fixed it. Each time with a different workaround. – Dpedrinha Nov 24 '16 at 19:00
12

I have met this problem. It's associated with the encoding of XAML files in VS. I'm using VS2015.

I solved this problem as follows:

  1. Open the *.xaml file in the project and click Save button. (There will be applying the correct encoding in VS2015).

  2. Then reopen the project and rebuild it. Now there are no errors.

wonea
  • 3,987
  • 17
  • 71
  • 134
Roman Himadinov
  • 321
  • 3
  • 5
11

This is probably not your case but I had similar problem and mine was xaml and code behind name missmatching. for example according to your sample, if code behind namespace is XamaTest(name of your app in most cases) and class is called MyXamlPage, your xaml class name must be XamaTest.MyXamlPage ([namespace].[classname])

I was silly after creating an empty xaml with code behind, I changed name of the class in xaml and i was getting this error.

<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
Emil
  • 5,290
  • 6
  • 47
  • 87
  • Worked. I renamed `Foo.xaml.cs` but forgot to change `x:Class="XXX.Foo"` (refatoring is bad in VS) – Hassan Tareq Feb 27 '19 at 16:12
  • THANK YOU!!! Been running around for hours with no working solution. It did the same thing - renamed the xaml. – Vering Mar 08 '19 at 12:44
5

Try adding a x:Name="..." on the xaml page... Nothing else worked for me - but after adding the x:Name attribute on some of the elements on the page the error dissapeared (most of the times - I still get it sometimes). I use the latest build (1.5.0.6447) of Xamarin.Forms...

XAML don't work on shared projects - it only works in portable projects...

Kim Rasmussen
  • 444
  • 1
  • 6
  • 20
  • 2
    I had 1 element/control that didn't have x:Name attribute on it..once i added that the error went away – David Oct 28 '15 at 21:12
4

I came across this error when;

  1. I removed a ContentPage-cs+xaml and the App-cs+xaml from the project without actually deleting it.
  2. Re-added these to the project in another folder.

This was fixed by;

  1. Select the .xaml file of the class in which the issue is present.
  2. Right click and select properties.
  3. In Build action select "Embedded Resource"
  4. In Custom Tool type "MSBuild:UpdateDesignTimeXaml"
  5. Clean and Build and it was gone.
wonea
  • 3,987
  • 17
  • 71
  • 134
7vikram7
  • 2,424
  • 1
  • 20
  • 38
4

Check page text x:Class="AppName.Page1". AppName must be your app name

Sᴀᴍ Onᴇᴌᴀ
  • 7,491
  • 8
  • 27
  • 56
3

It looks like the (re)generation of the blah.xaml.g.cs files is actually the problem. I get this a LOT in shared projects (which is why I don't use them unless I have no other choice). It happens way more in Xamarin Studio than Visual Studio, for me, for some reason. I try not to use XS at all.

Often unloading one of the other platforms (e.g. if you're building droid, unload ios) and doing a clean and rebuild will fix it.

You can also try doing something like opening one of the offending .xaml files and changing some of the xaml markup (e.g. adding or changing an x:Name to one of the controls or views). This will force a regeneration of the xaml.g.cs file, and (for me at least) usually solves the problem.

This really shouldn't be a thing tho.

wislon
  • 703
  • 5
  • 20
3

If you get intellisense errors such InitializeComponent in your Xamarin.Forms pages but the project actually builds and runs fine, just add a new Forms page using the wizard to fix all errors...

Then you can delete that new page.

Guillaume Perrot
  • 3,978
  • 2
  • 25
  • 33
2
  • I had similar problem in Visual Studio 2013 update 4 environment and I tried all recommendations what I found on the web. Nothing solved my problem.
  • Then I tried workaround approach. I installed Visual Studio 2015 preview and create new blank app with xamarin forms project.
  • When I added new Xaml file everything was OK and issue with InitialComponent method disappeared.
  • I don t know where exactly is the reason of the problem but it seems to be issue around configuration settings.
Nagama Inamdar
  • 2,801
  • 22
  • 38
  • 47
2

A Clean and rebuild did the trick for me!

machie27
  • 127
  • 1
  • 8
2

Right click *.xaml and click properties,and change "Custom Tool" value to "MSBuild:UpdateDesignTimeXaml", next change "Build Action" properties to "Embedded Resource", build project works.

Ali Yousefi
  • 2,099
  • 2
  • 26
  • 40
2

Very simple solution that worked for me:

  • Copy contents of the xaml/cs file
  • Delete the xaml/cs file
  • Create a new class and paste the contents

Now the InitializeComponent() function appears without red underline.

Hope this helps someone.

  • Yes, I found the same. Nothing worked. Eventually, copying the content, completely deleting the files and re-adding them from scratch was the only solution. – rob_james Jun 28 '18 at 11:03
2

Check the class name properly.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="{AppName}.{ClassName}">
</ContentPage>

The class name should be a combination of App name and partial class name

1

This problem appears when the projects of solution are referencing the version 1.4.0.0 of the dlls "Xamarin.Forms.Core", "Xamarin.Forms.Xaml" and "Xamarin.Forms.Platform" version 1.0.0.0.

To solve it I've had to downgrade to version 1.3.3.0 of the dlls but with this version Xamarin.Forms.Platform 1.0.0.0 don't exists.

Pulcker
  • 21
  • 2
1

Check the version of Xamarin.Forms package referenced in your project.

.csproj file Xamarin.Forms nuget package

user1412699
  • 1,435
  • 1
  • 10
  • 13
  • This answer worked, unload error containing proj and edit .csproj file to have xamarin version you have in package folder – shalin Sep 22 '17 at 08:02
1

I have been having the same issue now and then, and this is what I have been doing to fix it: When in the PCL project, I add a new cross-platform XAML page to the project. Adding a new XAML page takes a few seconds for the references to "hook". After the new XAML page is successfully added to the project, the red underlines on the XAML Pages (with issues) will get cleared. Once the problem is solved, I simply delete the XAML file that I have just added. - So, in summary, adding a new XAML page then deleting it has been solving the issue for me.

zinczinc
  • 518
  • 5
  • 9
1

I Just updated All packages, works fine.

Arun Prasad E S
  • 7,342
  • 6
  • 61
  • 75
1

I had a caching issue when I encountered this error.

To get this fixed, simply uninstall last version of Xamarin.Forms package and reinstall a previous working version.

When the rebuild is successful, then update the package again to the latest version.

Samuel Liew
  • 68,352
  • 105
  • 140
  • 225
Ali Yousefi
  • 2,099
  • 2
  • 26
  • 40
1

Change Page properties to :

BuildAction => Embedded resource 
CustomTools => MSBuild:UpdateDesignTimeXaml
M. Hamza Rajput
  • 3,508
  • 1
  • 20
  • 20
1

It appears this is caused by many things so if you've read all of these and haven't resolved it yet:

Mine was caused by the Solution Configuration being set to Release. Changed to Debug and error resolved.

Phil P
  • 141
  • 1
  • 5
0

I don't know if this is solved, but for me, the only thing I had to do is remove the first line of the XAML ("xml version="1.0" encoding="utf-8")

Sometimes source version control, tries to identify which type of file is and add this kind of stuff.

wonea
  • 3,987
  • 17
  • 71
  • 134
0

In my case the problem was the project path. The generated code file gets a name including the absolute path encoded to make it a valid filename. The path was "D:\Projekt C#\ProjectRootFolder\Project". The filename generated by the build tool was "Project.Droid.D_.Projekt_C_. Namespace etc." Moving the project to a path like "D:\project\ProjectRootFolder" helped in my case.

0

I'm using Visual Studio 2015, I got the same problem, and found none of the answers on the net was a full solution. Here I'll explain what worked for me.

My primary goal here was to eliminate the red error message that kept coming up

The name InitializeComponent does not exist in the current context

Basically I created a function called InitializeComponent2() that does exactly the same thing as InitializeComponent() and used that instead, I literally copied the code for InitializeComponent(). Does the job.

It looks like this (and I'll explain):

[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
private void InitializeComponent2()
{
    // Change to:
    //   this.LoadFromXaml(typeof(Page2)); // for Page2
    //   this.LoadFromXaml(typeof(Page3)); // for Page3
    // and put
    //   using Xamarin.Forms.Xaml;
    // at the top of each source file.
    this.LoadFromXaml(typeof(Page1));
}

Put the function in the definition of each of your pages (.cs files) e.g.

public partial class Page1 : ContentPage
{
    [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
    private void InitializeComponent2()
    {
        // Change to:
        //   this.LoadFromXaml(typeof(Page2)); // for Page2
        //   this.LoadFromXaml(typeof(Page3)); // for Page3
        // and put 
        //   using Xamarin.Forms.Xaml; 
        // at the top of each source file.
        this.LoadFromXaml(typeof(Page1));
    }
}

Also you need to put using Xamarin.Forms.Xaml; at the top of each .cs page where LoadFromXaml(..) is used.

And then of course change InitializeComponent() to InitializeComponent2() to call the new function. i.e. you have put the function into the same context as the page making the error go away. I can't imagine the real InitializeComponent function will get anything added to it as you modify your project but that is a possibility. It's been fine for me so far.

I tried many things, changing the Build Action, the XAML namespace, restarting vs, cleaning+rebuilding, looking for NuGet package updates.

Basically, Visual Studio compiled and ran the program fine on my android device + emulator, but that error message wouldn't go away. My solution is for Android, but it may also work for iOS etc.

I went back to the root of the problem InitializeComponent() The actual code for this function is generated in a file called <Your Project Name>.Page1.xaml.g.cs or Page2.xaml.g.cs for example. However, it (the file) is only generated when a certain event gets fired. I was lucky to discover it by typing text into "Custom Tool Namespace", which fired that event, for one of the xaml pages(a file ending in .xaml, not .cs - make sure you have .xaml file selected), type some text and press enter and the file will be created.

Then I had the great idea of making InitializeComponent2(), a function exactly the same as InitializeComponent() and putting it in each cs file so it exists without having to generate the .xaml.g.cs every time you want the error to go away.

wonea
  • 3,987
  • 17
  • 71
  • 134
Dougie
  • 1
0

add using Xamarin.Forms.Xaml

tested on Visual Studio 2017

0
  1. Select the App.xaml and MainPage.xaml file of the class in which the issue is present.
  2. Right click and select properties.
  3. In Build action select "Embedded Resource"
  4. In Custom Tool type "MSBuild:UpdateDesignTimeXaml"
  5. Clean and Build and it was gone.
ElasticCode
  • 5,312
  • 2
  • 22
  • 35
Endrit
  • 17
  • 6
0

Ultimate solution would be to edit the project file in a text editor and just copy the pattern from another non-conflicting file. This solution worked for me. Usually, you would look for this syntax:

<Compile Update="Your\Path\YourContentPage.xaml.cs">
  <DependentUpon>YourContentPage.xaml</DependentUpon>
</Compile>
mr5
  • 3,015
  • 3
  • 39
  • 54
0

In Xaml Page Properties only set
Build Action = Embedded resource
It works in visual studio 2017.

Saleem Kalro
  • 882
  • 8
  • 11
0

Tried all of the above and no luck, what did work for me was force reinstalling the Xamarin.Forms packages. In package manager console prompt;

update-package xamarin.forms -reinstall

It does not update packages, just removes and re-adds

0

I was missing a specific reference attribute (util in my case) in the root element:

<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="MyProject.Views.HomePage"
    xmlns:util="clr-namespace:Porject.Library.Util;assembly=Library"
    >
Jannie Theunissen
  • 21,664
  • 18
  • 85
  • 111
0

I Had the same issue with VS community edition 2019, i just used regenerate solution and the problem was fixed

0

For me it was just one rogue XAML with a leading space before <?xml version="1.0" encoding="utf-8" ?>, i.e.

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
...

resulting in a bunch of CS0103 The name 'InitializeComponent' does not exist in the current context errors.

daserge
  • 1,492
  • 11
  • 18