65.9K
CodeProject is changing. Read more.
Home

Custom WPF ListBox with Banding and Coloring in Code

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.60/5 (2 votes)

May 23, 2015

CPOL
viewsIcon

17983

Creating a custom ListBox by overriding the PrepareContainerForItemOverride() method of the ListBox with a custom routine.

Introduction

This tip is based on "Alternate Row Color in ListBox in WPF" by Diptimaya Patra
http://www.c-sharpcorner.com/uploadfile/dpatra/alternate-row-color-in-listbox-in-wpf/.

As I needed more than just the alternating row color (banding effect), instead of using Style.Triggers and AlternationCount in the XAML section, I opted to use a code-behind approach.

For this purpose, the PrepareContainerForItemOverride() method of the ListBox is replaced by a custom routine.

We can then do as we please with the ListBox rows, in the demo the property "StatusColor" of the Person class is used to change the color for Name 5 to red.

Using the Code

  1. Create a Visual Studio WPF project named "ListBoxSampleWPF".
  2. Copy the XAML code.
  3. Copy the C# code.

XAML

<Window x:Class="ListBoxSampleWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:ListBoxSampleWPF"
        Title="ListBoxCustom demo" Height="300" Width="300">

    <Grid>
        <my:ListBoxCustom x:Name="lbPersonList">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </my:ListBoxCustom>
    </Grid>

</Window>

C#

using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ListBoxSampleWPF
{
    /// <summary>
    /// Custom ListBox in WPF.
    /// Based on: "Alternate Row Color in ListBox in WPF" by Diptimaya Patra
    /// http://www.c-sharpcorner.com/uploadfile/dpatra/alternate-row-color-in-listbox-in-wpf/
    public partial class MainWindow : Window
    {
        ObservableCollection<Person> myList;

        public MainWindow()
        {
            InitializeComponent();
            myList = new ObservableCollection<Person>();

            for (int i = 0; i < 50; i++)
            {
                myList.Add(new Person { Name = "Name " + i, Age = i, StatusColor = null });
            }

            myList[5].StatusColor = Brushes.MistyRose;
            lbPersonList.ItemsSource = myList;
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public SolidColorBrush StatusColor { get; set; }
    }

    public class ListBoxCustom : ListBox
    {
        protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
        {
            base.PrepareContainerForItemOverride(element, item);
            int index = ItemContainerGenerator.IndexFromContainer(element);
            ListBoxItem lbItem = element as ListBoxItem;
            Person p = (Person)item;

            if (p.StatusColor != null)
            {
                lbItem.Background = p.StatusColor;
            }
            else if (index % 2 == 0)
            {
                lbItem.Background = Brushes.PaleTurquoise;
            }
            else
            {
                lbItem.Background = Brushes.White;
            }
        }
    }
}

Points of Interest

xmlns:my="clr-namespace:ListBoxSampleWPF"

In XAML is needed to set the namespace for ListBoxCustom which is in the code-behind.
We can then refer to it with "my:ListBoxCustom".

History

  • First version