Custom Styling the Alternate Rows inside ListView/GridView

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:local="using:wrt"
    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.
Leave a Comment
  • Please add 2 and 3 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Naomi  N edited Revision 1. Comment: Minor edit

  • Sachin  S edited Original. Comment: Added Pic

Page 1 of 1 (2 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
Page 1 of 1 (4 items)