ControlTemplate - Sample not working

Imagine if you want to standardize every page in your app with a header and/or footer. Or maybe you want to define a layout for a custom control. You can easily achieve this with a ControlTemplate.

A ControlTemplate enables you to define the visual structure of a page (ContentView or a ContentPage).

For example, you could define the following:


        ControlTemplate
        -Header
        -Content
        -Footer                      
                

And if you have the following ContentPage using the above ControlTemplate:


        ContentPage1
        -Label 1
                


        ContentPage1
        -Label 2
                

You will end up with:


        ContentPage1
        -Header
        -Label 1
        -Footer  
                


        ContentPage1
        -Header
        -Label 2
        -Footer  
                

Steps

1. Create a new .NET MAUI project.

2. In App.xaml add the following to define the layout of a ControlTemplate:


        <Application.Resources>
            <ResourceDictionary>                    
                <ControlTemplate x:Key="MyControlTemplate">
                    <StackLayout>
                        <Label Text="Header" FontSize="24" />
                        <ContentPresenter />
                        <Label Text="Footer" FontSize="24" />
                    </StackLayout>
                </ControlTemplate>                
            </ResourceDictionary>
        </Application.Resources>
                

3. Change MaingPage.xaml to the following:


        <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    x:Class="controltemplate.MainPage"
                    BackgroundColor="{DynamicResource SecondaryColor}"
                    ControlTemplate="{StaticResource MyControlTemplate}">        
           <Label Text="Hello World!" FontSize="18" />           
        </ContentPage>
                

The following define the use of the ControlTemplate defined in App.xaml.

ControlTemplate="{StaticResource MyControlTemplate}"

4. Run the app and you should see the header and footer added to the "Hello World!" label.

.NET MAUI