Click here to Skip to main content
15,893,401 members
Articles / Desktop Programming / WPF
Tip/Trick

Custom WPF ListBox with Banding and Coloring in Code

Rate me:
Please Sign up or sign in to vote.
2.60/5 (2 votes)
23 May 2015CPOL 17.2K   3   4
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

XML
<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#

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

XML
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Netherlands Netherlands
Software developer in the Netherlands, currently working on Video Surveillance applications.
Experience: C#, C++, VB, ASP, SQL Server, PostgreSQL, Gitea, TeamCity.
It all started with Black&White, no not the whiskey but the Sinclair ZX81 followed by several Atari's and PC's. The journey continues ...

Comments and Discussions

 
Questionno need to do.this Pin
Sacha Barber23-May-15 11:34
Sacha Barber23-May-15 11:34 
AnswerRe: no need to do.this Pin
RickZeeland23-May-15 20:32
mveRickZeeland23-May-15 20:32 
QuestionSome old news for you Pin
Kenneth Haugland23-May-15 5:05
mvaKenneth Haugland23-May-15 5:05 
AnswerRe: Some old news for you Pin
RickZeeland23-May-15 6:48
mveRickZeeland23-May-15 6:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.