TemplateSelector in .NET MAUI/Xamarin Forms

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.

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.


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





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



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dinesh Falwadiya

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