ContentPage.Content, do I need it?

NickANickA USMember ✭✭

I noticed when creating a new XAML page, the default includes <ContentPage.Content>. Do I need this?

According to the docs, the Content property "Gets or sets the view that contains the content of the Page." My page works fine without it, I just don't understand it's use. Is the default for a ContentPage Content? Any insight would be appreciated.

Answers

  • HarshitaHarshita INMember ✭✭✭

    both are applicable without having any issue :)

  • jezhjezh Member, Xamarin Team Xamurai
    edited March 8

    @NickA
    The ContentPage.Content always exists by default, even if you don't add it.

    First , when we check into ContentPage, we will find the Content is a Property of ContentPage.

    And when we create a Content page in C# as follows,

    we will find the detail of the new Page is

    namespace FormApp1
      {
       public class Page2 : ContentPage
      {
        public Page2 ()
        {
            Content = new StackLayout {  //Please note here : Content  Property
                Children = {
                    new Label { Text = "Welcome to Xamarin.Forms!" }
                }
            };
         }
         }
        }
    

    So we will know the Content is the view that contains the content of the Page just as the document says

    Besides, when we create a new XAML page, the code as follows

      <?xml version="1.0" encoding="utf-8" ?>
      <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:FormApp1"
             x:Class="FormApp1.MainPage">
        <ContentPage.Content  >
           <StackLayout>
           <!-- Place new controls here -->
             <Label Text="Welcome to Xamarin.Forms!" 
                 HorizontalOptions="Center"
                 VerticalOptions="CenterAndExpand" />
            </StackLayout>
         </ContentPage.Content>
    

    if we delete the <ContentPage.Content > and </ContentPage.Content>, the effect is the same, but the Content Property still exists by default.

    And when we edited code like this,

    we will find the error information: The property Content is set more that once. , so the ContentPage.Content is only one by default.

    Hope it can help you.

  • jezhjezh Member, Xamarin Team Xamurai
    edited March 14

    @NickA
    Have you got the solution?

Sign In or Register to comment.