Share via


Custom Styling the Alternate Rows inside ListView/GridView

To style the items inside ListView/GridView based on item index we will use StyleSelector to define custom styling for each item.

To implement this, we will define the class derived from StyleSelector as shown below.

Inside this class we are just returning the style which will apply background color based on Highlight properly of data model item.  

   class CustomStyleSelecter : StyleSelector
  {
      protected override  Style SelectStyleCore(object item, DependencyObject container)
      {
          SolidColorBrush highlight = (item as  ListVwItem).Highlight;
          Style style = new  Style(typeof(ListViewItem));
          style.Setters.Add(new Setter(Control.BackgroundProperty, highlight));
          return style;
      }
  }

Basically Highlight property returns the Solid Color Brush based on item index. 

   public SolidColorBrush Highlight 
        {
            get
            {
                if (Index % 2 == 0)
                   return new  SolidColorBrush(Colors.Brown);
                else
                   return new  SolidColorBrush(Colors.Wheat);
            }
        }

Another important thing to note is the use of Index to check if row is even or odd. Check out the implementation of Index property below:

  static int  _LastItemIndex = -1;
       int _Index = -1;
       public int  Index 
       {
           get
           {
               if (_Index == -1)
               {
                   _Index = ++_LastItemIndex;
               }
               return _Index;
           }
       }

We set _Index if it is -1 after incrementing the LastItemIndex.

Finally we define a custom style selector inside xaml and use it in ListView/GridView.

    <Page.Resources>
       <local:CustomStyleSelecter x:Key="customStyleSelector"/>
   </Page.Resources>
<ListView x:Name="gridView" ItemsSource="{Binding Items}"
                     ItemContainerStyleSelector="{StaticResource customStyleSelector}"
                     BorderBrush="Cyan" BorderThickness="3">
               <ListView.ItemTemplate>
                   <DataTemplate>
                           <StackPanel Background="{Binding Highlight}">
                               <TextBlock Text="{Binding Txt}" HorizontalAlignment="Stretch"/>
                           </StackPanel>
                   </DataTemplate>
               </ListView.ItemTemplate>
           </ListView>

Complete code listing below:

<Page
    x:Class="wrt.WrtPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:wrt"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
     
    <Page.Resources>
        <local:CustomStyleSelecter x:Key="customStyleSelector"/>
    </Page.Resources>
 
    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Orientation="Vertical">
            <ListView x:Name="gridView" ItemsSource="{Binding Items}"
                      ItemContainerStyleSelector="{StaticResource customStyleSelector}"
                      BorderBrush="Cyan" BorderThickness="3">
                <ListView.ItemTemplate>
                    <DataTemplate>
                            <StackPanel Background="{Binding Highlight}">
                                <TextBlock Text="{Binding Txt}" HorizontalAlignment="Stretch"/>
                                <!--<Image Source="{Binding ImageUri}" Height="60" Width="60"/>-->
                            </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackPanel>
    </Grid>
</Page>
namespace wrt
{
    class CustomStyleSelecter : StyleSelector
    {
        protected override Style SelectStyleCore(object item, DependencyObject container)
        {
            SolidColorBrush highlight = (item as ListVwItem).Highlight;
            Style style = new Style(typeof(ListViewItem));
            style.Setters.Add(new Setter(Control.BackgroundProperty, highlight));
            return style;
        }
    }
 
    class ListVwItem
    {
        static int _LastItemIndex = -1;
        int _Index = -1;
        public int Index 
        {
            get
            {
                if (_Index == -1)
                {
                    _Index = ++_LastItemIndex;
                }
                return _Index;
            }
        }
        public Uri ImageUri { get; set; }
        public string Txt { get; set; }
        public SolidColorBrush Highlight 
        {
            get
            {
                if (Index % 2 == 0)
                   return new SolidColorBrush(Colors.Brown);
                else
                   return new SolidColorBrush(Colors.Wheat);
            }
        }
    }
 
    class ListVwModel
    {
        public List<ListVwItem> Items { get; set; }
 
        public ListVwModel()
        {
             //Dummy Data
            Items = new List<ListVwItem>();
            Items.Add(new ListVwItem() { Txt = "Item 1" });
            Items.Add(new ListVwItem() { Txt = "Item 2" });
            Items.Add(new ListVwItem() { Txt = "Item 3" });
            Items.Add(new ListVwItem() { Txt = "Item 4" });
            Items.Add(new ListVwItem() { Txt = "Item 5" });
            Items.Add(new ListVwItem() { Txt = "Item 6" });
            Items.Add(new ListVwItem() { Txt = "Item 7" });
            Items.Add(new ListVwItem() { Txt = "Item 8" });
            Items.Add(new ListVwItem() { Txt = "Item 9" });
        }
    }
 
    public sealed partial class WrtPage : Page
    {
        public WrtPage()
        {
            this.InitializeComponent();
            this.DataContext = new ListVwModel();
 
        }
 
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
          
        }
    }
 
}

MSDN question here.