Custom Navigation bar with ControlTemplate in Xamarin Forms

Prateek
2 min readOct 17, 2019

--

Having a custom navigation bar which looks similar in both Android and iOS platforms with Xamarin forms has been a tough task. This is because android implements Toolbar natively and iOS has UINavigationBar, look and feel of both differ . Although we can make small changes and try to have similar look in both platforms with default NavigationBar implementation and its properties via NavigationPage.BarBackgroundColor,NavigationPage.BarTextColor, NavigationPage.HasNavigationBar , NavigationPage.HasBackButtonetcetera. But these properties are of limited scope and dont give much flexibility to put custom views.

Setting NavigationPage.TitleView

There is another way of customizing Navigation bar by making use of NavigationPage.TitleView .This is good, it accepts view and puts in the titlebar specified space, but there is default padding which makes it look bad if the background color you have chosen is different than ColorPrimary, this at least in the case of Android. Setting InsetPadding may fix this issue.

Code

Better Solution using ControlTemplate

We can use a templated page making use of ControlTemplate. In order to make this work we have to set the NavigationPage.HasNavigationBar to False

  1. First step is to create a static resource in ResourceDictionary i.e. in the App.xaml

2. Then in the page we set the ControlTemplate attribute with this.

3. Bindings in ControlTemplate

ControlTemplate supports special type of bindings called TemplateBindingTemplate bindings allow controls in a control template to data bind to public properties, enabling property values on controls in the control template to be easily changed.

To make it work we mostly set the TemplateBinding to Parent which means it binds to parent view which has used this controltemplate.

For ContentPage which has bindable properties in it we just use Parent (it will bind to code behind of the page) In MVVM pattern when we have viewmodel bound to ContengPage we can use Parent.BindingContext.Property to bind

On a ContentPage, the Content property can be assigned and the ControlTemplate property can also be set. When this occurs, if the ControlTemplate contains a ContentPresenter instance, the content assigned to the Content property will be presented by the ContentPresenter within the ControlTemplate.

We can also set ControlTemplate in Style

Advantages

  • ControlTemplate is flexible
  • Easily change at one place
  • Can be set in styles

In this article we learned about powers of ControlTemplate and how it can be beneficial in Xamarin forms to have a custom and uniform navigation bar .

--

--