How to create a custom ListView using DataTemplateSelector

Are you searching for a quick tutorial on how to create a chat UI in Xamarin Forms?

Are you looking for a customized ListView sample?

In this post, we will create a custom ListView and render it as a chat application.

 

There are times that you will need to render a collection of objects on your UI. Sometimes, you will also need to layout things that can’t be done in ViewCell. With these kinds of problem, the solution is to customize a DataTemplate so you can manipulate layouts based on certain conditions of your object’s properties.

Here are the steps on how to create and customize your DataTemplates.

 

Step 1:

Create a Sub-Class for DataTemplateSelector

When we inherit the DataTemplateSelector class, first we need to define the properties of the DataTemplate types as per our requirement. Once the properties are defined, then we need to overwrite OnSelectedTemplate method which returns the DataTemplate value. So while overriding the method, we can write our logic to verify which template should be used for the data object to display.

 

Step 2:

Add the xmlns reference for the Assembly

Since we need to refer the subclass of DataTemplateSelector, we need to add the XML namespace reference for the assembly within the content page of the XAML. To do this, we need to use xmlns : alias =”clr-namespace: namespace name; assembly = assembly name.

 

Step 3:

Create the DataTemplates as a ResourceDictionary

This is a requirement within the content page. To do this, we need to add a ResourceDictionary tag and then in order to define the DataTemplate we need to use DataTemplate. A valid name using x:Key and then we can use any valid XAML code to prepare the template.

 

Step 4:

Create an instance for DataTemplateSelector Sub-Class using the xml namespace alias.

Since we’ve used the xml namespace alias customListViewDemo, in order to create the instance we need to use customListViewDemo:ChatDataTemplateSelector x:Key equal to name. Then we need to bind the properties of the DataTemplateSelector with the DataTemplate defined within the content page. For example, FromTemplate equal to StaticResource FromTemplate and so on.

 

Step 5:

Bind the instance of DataTemplateSelector to ListView

Bind the DataTemplateSelector subclass instance as a StaticResource for the list item of ListView control. To do this, when we define the ListView control, we need to set the ItemTemplate property value with the DataTemplateSelector instance.

 

Step 6:

Build and run the demo app.

And here is the link to the GitHub repo of this tutorial so you can also see the model and mock data that I’ve used. https://github.com/webmasterdevlin/CustomListViewDemo

 

Hope this will give you an idea on how to create other custom layouts of ListView depending on your needs.

See you in my next post. Happy coding!