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

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:

Manage Your Windows Applications With Winget

Winget, Microsoft’s native package manager for Windows 10 (version 1709 and later) and Windows 11, offers a streamlined CLI for efficient application management. This blog post introduces Winget’s installation and basic commands for installing, updating, and removing software. It highlights the tool’s ability to manage non-Winget-installed apps and explores curated package lists for batch installations. The post also recommends top Winget packages, noting some may require a paid subscription.

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! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

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

Ready to come with us? 

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 contact form. 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.