.netxamllistviewuwplist-separator

ListView separator between items


I would like to insert a separator between items in a ListView, like in the image below.

Sample

There are 2 problems:

  1. If I add it (as a Border) at the bottom of the item in the ItemTemplate, the last item will have a separator, and it should not.
  2. If I find a way to add a separator outside the ItemTemplate, how would I align it to the labels?

Solution

  • 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

    enter image description here