Templates Come in many Shapes and Sizes

.Net Maui provides a set of templates to make your life easier. So, what is a template and why are they important? A template is a reusable piece of code. This is the very basic definition of a template. Really they are pieces of code that are reusable and therefore make your life easier because they contain code that is used again and again. They come in all shapes and sizes. Complex ones can be bound to data models, simple ones are self contained. Controls are really just another form of templates. In this post we will build a basic simple template. 

Introduction to the Header Template

So, in my app I want a common header to each page. It should have a logo, a background and have the ability to accept and display a title.

The Code.....

Let's start with the xaml, the UI part of the template

It defines a grid that has 3 rows and 4 columns. The logo takes up all three rows and sits in the first column. An interesting thing here is that he background fills the whole of the grid. The logo is then applied and goes over the top of the background. So from this we can say that the controls are layered onto the grid, one on top of the other. Here is the class for the template

As you can see the template accepts on property. the HeaderTitle. This was used in the XAML to set the text of the label 
Text="{Binding HeaderTitle}"
The binding works because of the Binding Context. It basically says to the template when you bind anything in the xaml get it from here, so in this case

this.BindingContext = this;

 We are binding ourselves to the context, so the xaml has access to the properties of the class.

So, We have a Template, How do we use it?

Now that wee have a template we want to use it in a page. This is very easily done.

First we add a reference to the templates:
xmlns:templates="clr-namespace:MulchFundraiserOrder.Templates"
which is saying you can use any of the items in the MulchFuncraiserOrder.Templates name space by using the templates name. So let's use one...
Wow, that was easy. We said use the Header template and set the title to Device Registration.
Here is what it looks like in my page...

And that is all there is to it. Of course, we can get a lot more detailed, binding to models etc... but that is for another day.


Comments

Popular posts from this blog

When Greed and Deception Destroy a Company

Let's Geocode with Here.com

I am Me, no excuses, just Me