Control Templates in Xamarin.Forms

This is the second post in the custom control series. You can read the first one where we created a custom control to select dates.


In this second post in the series, I want to show you when and how to use control templates. A primary reason to use control templates is when you need additional content inserted into a custom control at a pre-defined location. You can define a common UI that also displays unique content in different places. Check the references section at the end of this post to see other uses of control templates, such as redefining a control’s UI.
For your reference, I added a container custom control to our code sample repository. It’s a view with a header and an icon that can be tapped. Our content will be shown after the header. The header and the icon can be hidden, and we can bind a command to the icon.
In the following image, you can see three different instances of the custom control, each one with its own content.

Control Template Implementation

Usually, you will define the control template as a resource in a resource dictionary. In the following XAML code, I defined a control template and used the Key property to apply it to the ContentView with the ControlTemplate property. Instead of using Binding, I used the TemplateBinding markup extension that allows me to bind the ControlTemplate to properties defined on the custom control.
For example, the HeaderTitle property, defined in our custom control, will be used to set the text of the header. Using the ContentPresenter, I can set the place where the user content will be displayed. See the ContentPresenter tag in the sample XAML code below.

<ContentView xmlns="https://xamarin.com/schemas/2014/forms"
             xmlns:x="https://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="CustomControlsSample.Container"
             ControlTemplate="{DynamicResource ContainerTemplate}">
    <ContentView.Resources>
        <ResourceDictionary>
            <ControlTemplate x:Key="ContainerTemplate">
                <Frame Style="{DynamicResource FrameContainerStyle}">
                    <StackLayout Spacing="0">
                        <Grid Style="{DynamicResource BoxHeadTitleContainer}"
                            IsVisible="{TemplateBinding HeaderTitleIsVisible}">
                            <Label Style="{DynamicResource BoxHeadTitle}" Text="{TemplateBinding HeaderTitle}" />
                            <Image
                                Style="{DynamicResource BoxHeadIcon}"
                                IsVisible="{TemplateBinding IconIsVisible}">
                                <Image.Source>
                                    <!--Can't use style https://github.com/xamarin/Xamarin.Forms/issues/6421-->
                                    <FontImageSource
                                        Glyph="{TemplateBinding Icon}"
                                        Color="{DynamicResource BoxHeadTextColor}"
                                        FontFamily="FA"
                                        Size="18" />
                                </Image.Source>
                                <Image.GestureRecognizers>
                                    <TapGestureRecognizer Command="{TemplateBinding OnIconTappedCommand}"/>
                                </Image.GestureRecognizers>
                            </Image>
                        </Grid>
                        <StackLayout Style="{DynamicResource FrameContentStyle}">
                            <ContentPresenter />
                        </StackLayout>
                    </StackLayout>
                </Frame>
            </ControlTemplate>
        </ResourceDictionary>
    </ContentView.Resources>
</ContentView>

Consuming a Custom Control

In the MainPage.xaml file, you can see the use of the new custom control. Also, notice that I have the binding to MainPage’s command view model on line 6 to clean the dates when you tap on the icon, and the most important part, the user’s content starting in line 11 which will be shown inside the custom control. Notice that the line numbers I’m mentioning here are only for the partial code shown in this blog post, and not the full files in the code repository linked above.

.
.
.
<!--Select dates-->
<customcontrolssample:Container
    OnIconTappedCommand="{Binding CleanDate}"
    Icon="&#xf2ed;"
    IconIsVisible="True"
    HeaderTitle="Select your dates"
    HeaderTitleIsVisible="True">
    <StackLayout
        Padding="16">
        <customcontrolssample:CustomDateTimePicker
        SelectedDateTime="{Binding StartDateTime, Mode=TwoWay}"
        Caption="Start Date"/>
        <customcontrolssample:CustomDateTimePicker
        SelectedDateTime="{Binding EndDateTime, Mode=TwoWay}"
        Caption="End Date"/>
    </StackLayout>
</customcontrolssample:Container>
.
.
.

Check out the references section below to learn about how to use custom fonts.
That’s all for now, please let me know what do you think in the comments section. Thanks for reading!

References

Control Templates
Custom Fonts in Xamarin.Forms

Picture of Rodrigo Juarez

Rodrigo Juarez

Rodrigo Juarez has over 25 years of experience in software development, specializing in Microsoft technologies. His mission is to solve complex problems for his clients, with a focus on results. He achieves this by applying the appropriate technology and using best practices to ensure the delivery of high-quality solutions. Over the past 6 years, Rodrigo has honed his skills in back-end development and in creating mobile applications, initially using Xamarin and now transitioning to .NET MAUI. He is a Lead Mobile Developer at Trailhead Technology Partners and the co-author, along with Jesse Liberty, of the book ".NET MAUI for C# Developers"

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Custom Controls in Xamarin.Forms

When we want to reuse some of our user interface elements in a Xamarin.Forms application, one of the best ways to do it is by using custom controls. In this Github repository, I created a sample application with a custom control that is a c

Read More

Controls with NControl!

We occasionally want to include a specific UI design in our mobile apps that should look exactly the same on both Android and iOS, but we don't want to construct custom controls to do so. This is when the NControl package comes into play an

Read More

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.