title: Distinct item template for first and last item in a ListView
body: <p>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: <a href="https://stackoverflow.com/questions/7767097/use-different-template-for-last-item-in-a-wpf-itemscontrol/7767131#7767131">Use different template for last item in a WPF itemscontrol</a></p>
  
  <p>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).</p>
  
  <p>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?</p>
  
  <pre><code>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&lt;ListView&gt;(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;
      }
  }
  </code></pre>