Using a template selector is a powerful way of injecting different layouts based on the items that are being data-bound. In this case, we will look at each message that we want to display and select the best DataTemplate for them. The code is somewhat repetitive, so we will be using the same approach that we used for the XAML – simply adding the code and letting you study it yourself:
-
Create a folder called Selectors in the Chat project.
-
Create a new class called ChatMessageSelector in the Selectors folder and inherit it from DataTemplateSelector.
-
Add the following code, which will look at each object that is data-bound and pull the correct DataTemplate from the resources we just added:
using Chat.Messages;
using Xamarin.Forms;
namespace Chat.Selectors
{
public class ChatMessageSelector : DataTemplateSelector
{
protected override DataTemplate OnSelectTemplate(object
item, BindableObject container)
{
...