ListView data binding with mutiple data templates in Xamarin Forms

This article describes the ListView data binding with multiple data/item templates in Xamarin Forms. Since this feature is being implemented in Xamarin forms, it works in all the platforms windows, android & ios.

To use multiple data templates for a ListView, use DataTemplateSelector for selecting
the appropriate data template based on a type or a condition at runtime.

Note: To make use of DataTemplateSelector, ensure to update the Xamarin forms package to latest stable version (should be
>=2.1).

Let’s create a simple chat user interface and distinguish the messages as incoming
and outgoing as in below screenshot.

Create a Xamarin Forms project and update the Xamarin.forms package to latest stable
version.
Since ListView allows you to display a list of data using cells, create a custom
incoming message cell and outgoing message cell.

Create a ListView and apply the DataTemplateSelector by creating a static resource
with in the ResourceDictionary.
<ContentPage.Resources><ResourceDictionary><userControls:MessageTemplateSelectorx:Key="MessageTemplateSelector"></userControls:MessageTemplateSelector></ResourceDictionary>
</ContentPage.Resources><ListViewx:Name="lstMessages" HorizontalOptions="Fill"VerticalOptions="Fill" SeparatorVisibility="None"ItemTemplate="{StaticResource MessageTemplateSelector}"></ListView>