If we write large code in a XAML page, we have the possibility of getting some syntax errors but we will be unable to catch those XAML page issues until we run the application. It's a very bad experience for users.
To avoid this issue and catch XAML page related issues at compile time itself, Xamarin introduced 'XamlCompilation'. If we add this attribute in our xaml.cs file we can get XAML page related errors at compile time.
Here is the sample code for how to add this attribute to our XAML page.
FirstPage
- <?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="SampleProject.FirstPage">
-
- <Button Text="MoveToNextPage" HeightRequest = "40" WidthRequest = "150"
- VerticalOption="Center" HorizontalOptions="Center" OnClick = "On_Clicked"/>
- </ContentPage>
FirstPage.cs
- namespace SampleProject
- {
- public partial class SamplePage : ContentPage
- {
- public MainPage()
- {
- InitializeComponent();
- }
-
- Public void On_Clicked(Object sender, EventArgs e)
- {
- Navigation.PushAsync(new SamplePage());
- }
- }
- }
SamplePage
- <?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="SampleProject.SamplePage">
-
- <Label Text="Welcome to Xamarin Forms!" VerticalOption="Center" HorizontalOptions="Center" />
- </ContentPage>
SamplePage.cs
- namespace SampleProject
- {
- public partial class SamplePage : ContentPage
- {
- public MainPage()
- {
- InitializeComponent();
- }
- }
- }
In the above code, the sample XAML page contains one error; i.e., we write 'VerticalOption' instead of 'VerticalOptions' but we do not get any error up to run the application and open this page. When user runs the application it will open successfully and show the first page of the application without getting any problem. When a user clicks on 'MoveToPage' button on the first page it will navigate to SamplePage and application will crash due to an error in XAML page. We can avoid these type of errors by adding "XamlCompilation" attribute like below to our xaml.cs file.
SamplePage.cs
- [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
- namespace SampleProject
- {
- public partial class SamplePage : ContentPage
- {
- public MainPage()
- {
- InitializeComponent();
- }
- }
- }
After adding this attribute to your xaml.cs file and running the application you will get the error at compile time itself. So this attribute is greatly helpful for us if we write large XAML pages and try to find out what is missing in that file for resolving those issues.