Xamarin.Forms: Customize ListView
Posted on September 12, 2016 • 2 minutes • 278 words
Table of contents
In this post i want to show you how you can customize a Listview. I will create a ListView with different Layouts for the items.
Create your model class
using System;
using System.Collections.Generic;
namespace Dependencytest
{
public class Message
{
public string type { get; set; }
public string text { get; set; }
public string time { get; set; }
public Message(string type, string text,string time )
{
this.type = type;
this.text = text;
this.time = time;
}
public static List<Message> getMessages() {
List<Message> messageList = new List<Message>();
messageList.Add(new Message("incoming","This message was incoming","10:00:05"));
messageList.Add(new Message("outgoing", "This message was outgoing", "10:00:08"));
messageList.Add(new Message("incoming", "This message was also incoming", "10:00:10"));
return messageList;
}
}
}
Create a DataTemplateSelector
using System;
using System.Diagnostics.Contracts;
using Xamarin.Forms;
namespace Dependencytest
{
public class MyTemplateSelector : DataTemplateSelector
{
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
Message message = item as Message;
DataTemplate personDataTemplate = new DataTemplate(() =>
{
if (message.type.Equals("incoming")){
return new IncomingMessageViewCell(message);
}
if (message.type.Equals("outgoing"))
{
return new OutgoingMessageViewCell(message);
}
return new ViewCell();
});
return personDataTemplate;
}
}
}
Create a Custom ViewCell
The IncomingMessageViewCell looks the same except that this class has the Layout aligned to the right side.
OutgoingMessageViewCell.xaml.cs
<?xml version="1.0" encoding="UTF-8"?>
<ViewCell xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Dependencytest.OutgoingMessageViewCell">
<ViewCell.View>
<StackLayout HorizontalOptions="End" BackgroundColor="Lime">
<Label x:Name="lblMessage"></Label>
<Label x:Name="lblTime"></Label>
</StackLayout>
</ViewCell.View>
</ViewCell>
OutgoingMessageViewCell.cs
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace Dependencytest
{
public partial class OutgoingMessageViewCell : ViewCell
{
public OutgoingMessageViewCell(Message message)
{
InitializeComponent();
lblMessage.Text = message.text;
lblTime.Text = message.time;
}
}
}
Add the Data and TemplateSelector to your ListView
If your ListView has items with different heights you need set HasUnevenRows to true.
listView.HasUnevenRows = true;
listView.ItemsSource = Message.getMessages();
listView.ItemTemplate = new MyTemplateSelector();