xamarin.formscontent-pages

Xamarin.Forms: Can I embed one ContentPage or ContentView into another ContentPage


I have multiple ContentPage xaml files in my Xamarin project. I want to embed a shared piece of xaml into each ContentPage. There is nothing particularly special about the shared piece of xaml (it does't need to do anything platform specific). Shouldn't it be just as easy as embedding a tag in the xaml of the ContentPage to include the shared xaml file? Can someone point me in the right direction?


Solution

  • You can take the parent child of your ContentPage (for example, a StackLayout that wraps all the children), put it in an external xaml file, and then include that component in each one of your ContentPages.

    The external xaml file will be a StackLayout type, rather than a ContentPage.

    Edit - added a code sample:

    Let's add a header StackLayout: we add a code behind class:

    public partial class HeaderNavigationBar 
    {
        public HeaderNavigationBar()
        {
            InitializeComponent();
        }
    }
    

    Then add the XAML code:

    <StackLayout x:Class="HeaderNavigationBar"
                 Orientation="Horizontal"
                 HorizontalOptions="FillAndExpand"
                 Padding="10"
                 BackgroundColor="White">
    
        <Image Source="burger_icon"
               HorizontalOptions="StartAndExpand"
               Aspect="AspectFit">
            <Image.GestureRecognizers>
                <TapGestureRecognizer Command="{Binding SlideNavigationDrawerCommand}" />
            </Image.GestureRecognizers>
        </Image>
    </StackLayout>
    

    And finally, in the page where you want to reuse your component - add this reference:<HeaderNavigationBar />.