Xamarin Forms Page Templates

Coming from a web background, I was used to having a master page that normally contained a header and footer and then let the individual pages define the content, I was disappointed that I couldn’t do that on Xamarin Forms. In order to compensate for this we needed to create a control and reference it on every page. Not a particularly clean solution but it worked.

All that changed with the release of Xamarin Forms 2.1.0, when ControlTemplate and TemplatedPage were introduced. After some deciphering of the documentation I finally figured out it was incredibly easy to do. Here is how to create a template and apply it to any existing ContentPage. In this scenario I am just going to add a header label to a ContentPage.

Define the ControlTemplate

The first step is to go to your App.xaml and add a ControlTemplate to your ResourceDictionary. The ControlTemplate allows you to provide the VisualElement’s you want displayed.


You will also notice something called the ContentPresenter. This is the placeholder for where the VisualElement’s defined on the ContentPage will appear.

Note: If you only have an App.cs in your main project, check out the section in Styling on how to replace it with an App.xaml and App.xaml.cs

Apply the ControlTemplate

Next all you need to do is go to any ContentPage (which inherits from TemplatedPage) and set the ControlTemplate.

Binding to the ContentPage

On a brief side tangent, if you want your header to receive values from the ContentPage you applied it to you can do this using TemplateBinding, instead of just Binding. You would also need to make sure an INPC property was available in the BindingContext of the ContentPage.

Final Result

All elements are shown on the screen and no longer do we need to create a control and reference it on every page. This is an incredibly simple example but it provides a solid base to expand on to meet your needs. Happy templating.

TemplateExample1


Posted

in

,

by

Tags: