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();
}
}
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:
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.
I get this sometimes and here's the checklist that solved them so far:
Make sure the namespace in .xaml and .xaml.cs match
Inherit from the correct parent - ContentPage for a page and ContentView for a control
Set build action of the .xaml file to Embedded Resource if in the shared project.
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.
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:
Open the *.xaml file in the project and click Save button. (There will be applying the correct encoding in VS2015).
Then reopen the project and rebuild it. Now there are no errors.
Updating the Xamarin.Forms NuGet package should do the job
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
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...
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.
I came across this error when;
I removed a ContentPage-cs+xaml and the App-cs+xaml from the project without actually deleting it.
Re-added these to the project in another folder.
This was fixed by;
Select the .xaml file of the class in which the issue is present.
Right click and select properties.
In Build action select "Embedded Resource"
In Custom Tool type "MSBuild:UpdateDesignTimeXaml"
Clean and Build and it was gone.
Check page text x:Class="AppName.Page1". AppName must be your app name
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.
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.
A Clean and rebuild did the trick for me!
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.
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.
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
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.
Check the version of Xamarin.Forms package referenced in your project.
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.
I Just updated All packages, works fine.
Change Page properties to :
BuildAction => Embedded resource
CustomTools => MSBuild:UpdateDesignTimeXaml
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.
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.
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.
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.
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.
add using Xamarin.Forms.Xaml
tested on Visual Studio 2017
Select the App.xaml and MainPage.xaml file of the class in which the issue is present.
Right click and select properties.
In Build action select "Embedded Resource"
In Custom Tool type "MSBuild:UpdateDesignTimeXaml"
Clean and Build and it was gone.
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>
In Xaml Page Properties only set
Build Action = Embedded resource
It works in visual studio 2017.
Related
I'm new to Xamarin development, but try to be exact.
Using Visual Studio 2022, with Xamarin version 17.0.0.182 (as displayed in VS About).
Found this great article on how to use Bootstrap icons, but it seems to be out of date. When I followed the steps and provided hex codes for the characters, I didn't get the expected glyiphs.
I found that
new Xamarin needs new methods,
new Bootstrap fonts need new ways.
Here they are.
1.) Get the font from the Bootstrap github repo at https://github.com/twbs/icons
Go to releases (https://github.com/twbs/icons/releases), choose latest, scroll down to Assets, download the bootstrap-icons-x.x.x.xip file.
Unzip it, and find fonts/bootstrap-icons.woff.
Not something you can use in Xamarin right away :-(
2.) Convert the woff file to ttf
I googled for a converter and used https://cloudconvert.com/woff-to-ttf
Now you have the ttf you need :-)
3.) Now follow the current Xamarin method of adding a font to your app.
The process is described here: https://devblogs.microsoft.com/xamarin/embedded-fonts-xamarin-forms/
In short:
add the ttf file to the shared Xamarin project, Embedded Resources / Fonts
change file properties / Build Action to "Embedded resource"
register the font by adding a line to the end of Assemblyinfo.cs:
[assembly: ExportFont("bootstrap-icons.ttf", Alias = "Bootstrap")]
4.) Use it in xaml like
<Label FontFamily="Bootstrap" Text=""/>
to display a magnifying glass.
You may also define a Label style, but I'll skip that for now.
4/b.) To use it in xaml via binding
Oh, if things were easy...
When using a binding to display a glyph, there's one more hoop to jump, thanks to these guys for the solution: Using data binding, how do I bind text which contains emojis to a label and have it display correctly?
So, in xaml:
<!-- set BindingContext to MyViewModel -->
<Label FontFamily="Bootstrap" Text="{Binding StateIconName}" />
in your MyViewModel:
public string StateIconName
{
get => WebUtility.HtmlDecode("");
}
5.) To browse available glyphs (icons)
Open the overview page: https://icons.getbootstrap.com/
6.) To find the unicode character code, also referred to as "Unicode HTML Entity"
Check the name of the icon above in step 5.
Open the Bootstrap-icons.css file from Github: https://github.com/twbs/icons/blob/main/font/bootstrap-icons.css
Search for the name of the glyph to find the character code, something like:
.bi-zoom-in::before { content: "\f62c"; }
Use this code in xaml like
Given some Xaml like this:
<headingView:HeadingView
x:Class="Test.Views.Decks.DeckBase.DeckMgmt.DeckMgmtPage2"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:headingView="clr-namespace:Test.Templates.Pages.HeadingView;assembly=Test"
xmlns:t="clr-namespace:Test.Templates"
BackIconVisible="True"
PageTitle="Mgmt">
<t:Stack>
<t:ContentFrame Heading="Reset">
<t:LinkGrid TapCommand="{Binding ResetDeckCmd}" Text1="Reset" />
</t:ContentFrame>
<t:ContentFrame Heading="Sort">
<t:LinkGrid Text1="Sort" />
</t:ContentFrame>
</t:Stack>
</headingView:HeadingView>
I don't need help in changing this to C# but I would like to know if there is any place or way I can find out the intermediate C# that is created?
Viewing the actual code generated by the compiler is tricky (I tried for a couple of hours but I could not find a way to directly view the code) - but it is possible to view the source code itself.
First of all - download .NET reflector and the appropriate Visual Studio extension.
https://visualstudio.microsoft.com/vs/preview/
Now we need to find the method that we want to decompile.
The method Xamarin.Forms.Xaml.Extensions.LoadFromXaml() is found in your page's xaml.g.cs file. According to Microsoft:
When Visual Studio builds a project containing a XAML file, it [the method] parses the XAML file to generate a C# code file (for example, MainPage.xaml.g.cs) that contains the definition of the InitializeComponent method:
The method in this case is the LoadFromXaml() method.
Now add a breakpoint like so:
Press F12 until you reach the following:
You will reach the 'Load' method:
You will see something like this:
From here - you can browse the rest of the XamlLoader class's source code:
Very interesting, isn't it? This is the closest thing to a solution that I got to.
I've just shared it as an image as I don't think it would be appropriate to share the full code as a code snippet.
It's not exactly what you're looking for - but I still hope this helped answer your question either way.
I have a WebView that shows the terms and conditions when the user starts the app. That WebView contains a few links. Currently, I have the terms and conditions as a html file that I store in resources.
In the code-behind I fill the WebView via:
public partial class Agb : ContentPage
{
public Agb()
{
InitializeComponent();
BindingContext = new ViewModel.AgbViewModel();
Web.Source = new HtmlWebViewSource
{
Html = Properties.Resources.Agb
};
Web.Navigating += WebViewNavigating;
}
XML:
<WebView
x:Name="Web"
VerticalOptions="FillAndExpand"
Margin="50,0"/>
Most of the time this works well. On UWP this WebView sometimes fails to show. It always shows on my own computer but randomly fails in production.
Is there anything I can do to get the WebView to work reliably?
Option 1:
I've made a pull request to fix this bug in Xamarin.Forms, so simply update Xamarin.Forms to a version, where it will be merged.
However, while the fix is not yet there and while the fix may not be available for earlier versions of Xamarin.Forms before 4.4.0, here's how to fix it in your project:
Option 2
Add the WebViewRenderer_fix.cs file to your project. This file is based on v4.4.0, but if you see build errors, you may need to apply the fix yourself to earlier version of this file.
And don't forget to register it as a custom renderer for your WebView
[assembly: ExportRenderer(typeof(WebView), typeof(WebViewRenderer_fix))]
I've got a Xamarin.Forms app. at one time, I had this working, but alas, something has happened and now it no longer works. In my Android project, I have a dependency service as shown below. I am just trying to play a sound on the local system in the background. Now, out of the blue, I am getting an error on compile saying that 'Resource' does not contain a definition for 'Raw'. I have no idea where this error came from or how to fix it. There is a directory in Resource folder called raw. In it, there is a file named flushing.mp3. the VS intellisense does indicate the file is there. Any ideas are appreciated. TIA
Here is my code for my dependency service:
[assembly: Dependency(typeof(Audio))]
namespace PooperAppMobile.Droid.DependencyServices
{
public class Audio : IAudio
{
private MediaPlayer _mediaPlayer;
public bool PlayFlush()
{
_mediaPlayer = MediaPlayer.Create(global::Android.App.Application.Context, Resource.Raw.flushing);
_mediaPlayer.Start();
return true;
}
}
}
Well to be quite honest this error was giving me quite a pain when I saw this solution on a GITHUB discussion now all you have to do is add this line in your project file i.e. the .csproj, in your debug property group something like this :
<PropertyGroup.......
<AndroidUseManagedDesignTimeResourceGenerator>False</AndroidUseManagedDesignTimeResourceGenerator>
....
</PropertyGroup>
And It will start working as expected,
Good luck!
In case of queries do revert.
I am trying to create a new page to my solution but I can't run the emulator because when I try to build the app I get the error CS0103: The name 'InitializeComponent' does not exist in the current context.
I tried what is in this
https://forums.xamarin.com/discussion/62671/initializecomponent-does-not-exist-in-the-current-context-error
which basically says change the the "Build Action" to "Embeded Source". I tried it and the red squiggly line bellow the "Initialize Component" disappears but when i try to reference to that page for example when i want to open the page when a button is clicked I can't reference the page, the name doesn't come up with the intelliscence as it type the word "page1" an I get an error when i try to build the solution because it says " the type or namespace named page1 can not be found, are you missing using a directive or an assembly reference.
also another page suggests changing the page1.xaml build action to embeded source and making the page1.xaml.cs build action to compile. I can't do this because the page1.xaml doesn't get added to he solution explorer when I create a new page. so I can't select property and change the build action for page1.xaml.
also this page doesn't work because it is about wpf not xamarin.
The name 'InitializeComponent' does not exist in the current context.
this link sais that the project runs fine although he has a red squigly line under the initialize component which isn't my case.
https://github.com/UXDivers/Grial-UI-Kit-Support/issues/154
this one sais clean and rebuild solves the build erro but it is not true in my case.
https://github.com/xamarin/Xamarin.Forms/issues/2863
This issue occurs if the xaml and xaml.cs page is not connected properly.
Xaml Page
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:controls="EmployeeApp.PettyCashListPage" x:Class="EmployeeApp.PettyCashListPage">
x:Class="EmployeeApp.PettyCashListPage"
Xaml.cs
public partial class PettyCashListPage : ContentPage
Both class name should match, if not 'InitializeComponent' issue occurs. Hope this helps.
The Problem was that I hadn't included the Universal Windows Platform tools for Xamarin package when I installed the application. After installing that package , it now works perfectly.
A little side note: when I tried creating a new page before installing the package mentioned I used to get only the page.xaml.cs in the solution explorer. But after installing it , I now get both the page.xaml and the page.xamal.cs in the solution explorer and the problem is solved.