Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6730821
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T10:27:17+00:00 2026-05-26T10:27:17+00:00

I need to style the first and last items of a list view differently.

  • 0

I need to style the first and last items of a list view differently. To achieve that, I started working on a solution based on that answer: Use different template for last item in a WPF itemscontrol

Basically, I have a custom ItemsTemplateSelector that decide on the template to apply based on the item’s index in the list view items (code below).

It works properly except that when the list gets updated (an item is added or removed), the templates do not get selected again (for instance, initially, the SingleItemTemplate gets selected because there is a single item. When I add an item to the list, that first item’s template does not get switched to FirstItemTemplate). How to force template selection for all items?

public class FirstLastTemplateSelector : DataTemplateSelector 
{
    public DataTemplate DefaultTemplate { get; set; }
    public DataTemplate FirstItemTemplate { get; set; }
    public DataTemplate LastItemTemplate { get; set; }
    public DataTemplate SingleItemTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        ListView lv = VisualTreeHelperEx.FindParentOfType<ListView>(container);
        if (lv != null)
        {
            if (lv.Items.Count == 1)
            {
                return SingleItemTemplate;
            }

            int i = lv.Items.IndexOf(item);
            if (i == 0)
            {
                return FirstItemTemplate;
            }
            else if (i == lv.Items.Count - 1)
            {
                return LastItemTemplate;
            }
        }
        return DefaultTemplate;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T10:27:18+00:00Added an answer on May 26, 2026 at 10:27 am

    As an alternative approach, I would suggest binding the AlternationCount of your ItemsControl to the number of items in your collection (e.g. the Count property). This will then assign to each container in your ItemsControl a unique AlternationIndex (0, 1, 2, … Count-1). See here for more information:

    http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.alternationcount.aspx

    Once each container has a unique AlternationIndex you can use a DataTrigger in your container Style to set the ItemTemplate based off of the index. This could be done using a MultiBinding with a converter that returns True if the index is equal the count, False otherwise. Of course you could also build a selector around this approach as well. With the exception of the converter, this approach is nice since it is a XAML only solution.

    An example using a ListBox:

    <Window x:Class="WpfApplication4.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:Collections="clr-namespace:System.Collections;assembly=mscorlib"
            xmlns:System="clr-namespace:System;assembly=mscorlib"
            xmlns:l="clr-namespace:WpfApplication4"
            Title="MainWindow" Height="350" Width="525">
        <Grid>
            <Grid.Resources>
                <Collections:ArrayList x:Key="MyCollection">
                    <System:String>Item One</System:String>
                    <System:String>Item Two</System:String>
                    <System:String>Item Three</System:String>
                </Collections:ArrayList>
    
                <l:MyAlternationEqualityConverter x:Key="MyAlternationEqualityConverter" />
    
                <Style x:Key="MyListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
                    <Style.Triggers>
                        <DataTrigger Value="True">
                            <DataTrigger.Binding>
                                <MultiBinding Converter="{StaticResource MyAlternationEqualityConverter}">
                                    <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ListBox}}" Path="Items.Count" />
                                    <Binding RelativeSource="{RelativeSource Self}" Path="(ItemsControl.AlternationIndex)" />
                                </MultiBinding>
                            </DataTrigger.Binding>
                            <!-- Could set the ItemTemplate instead -->
                            <Setter Property="Background" Value="Red"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Grid.Resources>
    
            <ListBox ItemsSource="{Binding Source={StaticResource MyCollection}}"
                     AlternationCount="{Binding RelativeSource={RelativeSource Self}, Path=Items.Count}"
                     ItemContainerStyle="{StaticResource MyListBoxItemStyle}" />
        </Grid>
    

    Where the converter might look something like:

    class MyAlternationEqualityConverter : IMultiValueConverter
    {
        #region Implementation of IMultiValueConverter
    
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (values != null && values.Length == 2 &&
                values[0] is int && values[1] is int)
            {
                return Equals((int) values[0], (int) values[1] + 1);
            }
    
            return DependencyProperty.UnsetValue;
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    
        #endregion
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I hava a php variable that contain JSON type data. $list = [{id:10,first_name:first,mi_name:,last_name:last,nick_name:HH}]; and
I need to fetch a list items available in a website that list the
I need to style a regular html list like the following picture: as you
I've got an HTML select box that I need to style. I'd prefer to
I'm working on pypreprocessor which is a preprocessor that takes c-style directives and I've
I need to do the active class will move from the first list item
I have a field that a user can input first and last name to
I have the following view that i need to display an error message when
I need to style the default delete button on a tableview cell in objective
I need to style a ton of different elements (read: cells) in a PDF

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.