TemplateSelector in .NET MAUI/Xamarin Forms

Dinesh Falwadiya
2 min readOct 26, 2022

Hi Guys, In this blog, we will learn how to use DataTemplate & TemplateSelector in .NET MAUI/Xamarin Forms.

DataTemplate helps us define the Template of Data to be shown, which can also be reused. DataTemplates also make it easy to manage the code.

DataTemplateSelector is used to choose or select the DataTemplate defined based on the Data State at Runtime.

Output

DataTemplateSelector Implementation

To define DataTemplateSelector we need to create a class that extends from DataTemplateSelector class.

public class UserTemplateSelector : DataTemplateSelector

And, now define the DataTemplates as per our requirements & override OnSelectTemplate method to choose or select DataTemplate based on data state/type.

Consuming DataTemplateSelector

To use the DataTemplateSelector we created above we first need to include the namespace of our DataTemplateSelector

In my case, I created a separate folder named TemplateSelectors for UserTemplateSelctor class.

xmlns:templateSelector="clr-namespace:MyApp.TemplateSelectors"

Now let’s define 3 DataTemplates for Default User, VIP User & Blacklisted User as shown below.

Note: Each DataTemplate is given a unique key using x:Key attribute & the DataTemplateSelector is also given a key to be used later.

Finally, simply use this DataTemplateSelector Key inside ListView or any other view which supports DataTemplateSelector.

<ListView ItemTemplate="{StaticResource userTemplateSelector}"/>

Sample App Code

User Model

UserTemplateSelector

MainPage.xaml

MainPage.xaml.cs

Output

Thanks for following the blog till here. Happy Coding :D

Sign up to discover human stories that deepen your understanding of the world.

Dinesh Falwadiya
Dinesh Falwadiya

Written by Dinesh Falwadiya

Mobile app developer who loves to share his knowledge and get improve with others.

No responses yet

Write a response

Recommended from Medium

Lists

See more recommendations