I would like to insert a separator between items in a ListView
, like in the image below.
There are 2 problems:
ItemTemplate
, the last item will have a separator, and it should not.ItemTemplate
, how would I align it to the labels?You need to use a DataTemplateSelector
for this. First you need to create Two DataTemplate
's
For example: In a simple ItemsControl which I want to show you a list of String, My Two DataTemplate
's would look like below.
<Page.Resources>
<DataTemplate x:Name="AllItems">
<Border BorderBrush="{StaticResource SystemControlBackgroundBaseLowBrush}" BorderThickness="0,0,0,2">
<TextBlock Text="{Binding ''}" Padding="10" Margin="10,0" />
</Border>
</DataTemplate>
<DataTemplate x:Name="LastItems">
<TextBlock Text="{Binding ''}" Padding="10" Margin="10,0" />
</DataTemplate>
</Page.Resources>
Now I create a DataTemplateSelector
and Check if the Item that I need to apply the DataTemplate
is Last one or not.
public class ItemsDataTemplateSelector: DataTemplateSelector
{
public DataTemplate AllItems { get; set; }
public DataTemplate LastItems { get; set; }
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
DataTemplate _returnTemplate = new DataTemplate();
var itemsControl = ItemsControl.ItemsControlFromItemContainer(container);
if (itemsControl.IndexFromContainer(container) == (itemsControl.ItemsSource as List<String>).Count-1)
{
_returnTemplate = LastItems;
}
else
{
_returnTemplate = AllItems;
}
return _returnTemplate;
}
}
Now my ItemsControl
Implementation would be
<ItemsControl x:Name="listView">
<ItemsControl.ItemTemplateSelector>
<local:ItemsDataTemplateSelector AllItems="{StaticResource AllItems}" LastItems="{StaticResource LastItems}" />
</ItemsControl.ItemTemplateSelector>
</ItemsControl>
Here is how i set the ItemsSource to ItemsControl
List<String> items = new List<string>();
for (int i = 1; i <= 5; i++)
{
items.Add("Item " + i.ToString());
}
listView.ItemsSource = items;
Below is your output. You can see Last Item does not have a Border