Click here to Skip to main content
11,413,548 members (70,725 online)
Click here to Skip to main content

Highlighting Items in a WPF ListView

, 28 Apr 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
A step-by-step review of how to conditionally highlight ListViewItems.
Screenshot - HighlightingItemsInWPFListView.png


This article shows how to change the color of items in a ListView, based on values in or associated with the item. The technique used here binds a ListView to an ADO.NET DataTable, and makes use of a custom value converter to determine what color each ListViewItem should be.


Here's a common scenario: you have a DataTable which needs to be displayed in a ListView, and any row which contains a value in some certain range (say, less than zero) should be "highlighted" with a special color. Perhaps the value which determines the ListViewItem's color is not even displayed in the ListView, but only exists in a DataRow. How might one implement that functionality in WPF?

There are four steps involved with this task:

  1. Populate a DataTable and bind it to a ListView.
  2. Specify how the ListView should display the DataTable (i.e. specify where the items come from, configure the columns, etc.).
  3. Write a Style which highlights ListViewItems.
  4. Create a class which helps determine a ListViewItem's color.

This article's demo application creates a simple DataTable, which contains a customer ID, name, and balance. If the customer is owed money (i.e. her balance is negative) then that customer's item is highlighted red. If the customer owes money, then the item is green.

Step one - Populate a DataTable and bind it to a ListView

Let's assume that our Window subclass contains a ListView in it, named 'listView'. First we must create the DataTable and set it as the ListView's DataContext.

public Window1()
 this.listView.DataContext = CreateDataTable();

// In a real app the DataTable would be populated from a database
// but in this simple demo the dummy data is created locally.
DataTable CreateDataTable()
 DataTable tbl = new DataTable( "Customers" );

 tbl.Columns.Add( "ID", typeof( int ) );
 tbl.Columns.Add( "Name", typeof( string ) );
 tbl.Columns.Add( "Balance", typeof( decimal ) );

 tbl.Rows.Add( 1, "John Doe", 100m );
 tbl.Rows.Add( 2, "Jane Dorkenheimer", -209m );
 tbl.Rows.Add( 3, "Fred Porkroomio", 0m );
 tbl.Rows.Add( 4, "Mike Spike", 550m );
 tbl.Rows.Add( 5, "Doris Yakovakovich", 0m );
 tbl.Rows.Add( 6, "Boris Zinkwolf", -25m );

 return tbl;

Step two - Specify how the ListView should display the DataTable

Now that the DataTable is ready and available to be displayed, let's see how to show it in a ListView.

  ItemContainerStyle="{StaticResource ItemContStyle}"
      <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" />
      <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" />
      <GridViewColumn Header="Balance" Width="140">
            <TextBlock Text="{Binding Balance}" TextAlignment="Right" />

In the Window's constructor we assigned a DataTable to the ListView's DataContext, so setting its ItemsSource property to '{Binding}' means to simply bind against that DataTable. Each column displayed in the ListView is represented by a GridViewColumn. The 'Balance' column's CellTemplate is set (as opposed to using the DisplayMemberBinding) so that the monetary value can be right-aligned, which is typical for displaying numeric values.

The ListView's ItemContainerStyle property is set to a Style, which is yet to be shown. ItemContainerStyle is used because that property affects the Style property of each ListViewItem generated by the ListView. Since we want to highlight an entire ListViewItem that property is the logical place to apply our "highlight style".

Step three - Write a Style which highlights ListViewItems

In the previous section, the ListView's ItemContainerStyle was set to a Style whose key is 'ItemContStyle'. That Style is seen below:

<Style x:Key="ItemContStyle" TargetType="{x:Type ListViewItem}">
    <!-- Brushes omitted for clarity… -->
    <!-- Reduces a customer's Balance to either -1, 0, or +1 -->
    <local:NumberToPolarValueConverter x:Key="PolarValueConv" />

  <!-- Stretch the content so that we can right-align values
       in the Balance column. -->
  <Setter Property="HorizontalContentAlignment" Value="Stretch" />

    <!-- When a customer owes money, color them green. -->
      Binding="{Binding Balance, Converter={StaticResource PolarValueConv}}"
      <Setter Property="Background" Value="{StaticResource ProfitBrush}" />

    <!-- When a customer is owed money, color them red. -->
      Binding="{Binding Balance, Converter={StaticResource PolarValueConv}}"
      <Setter Property="Background" Value="{StaticResource LossBrush}" />

The Style sets two properties on each ListViewItem: HorizontalContentAlignment and Background. The former is set to 'Stretch' so that the elements in the ListView's "cells" will occupy the entire surface area of those cells. That allows us to right-align the text in the 'Balance' column.

The Background property of each ListViewItem is conditionally set to a "highlight brush" based on the customer's 'Balance' value. A DataTrigger is used to evaluate a customer's 'Balance' value and then, if the customer either owes money or is owed money, that customer's ListViewItem will have its Background set to the appropriate brush.

Step four - Create a class which helps determine a ListViewItem's color

The DataTriggers seen in the previous section use a custom value converter in their Bindings, called NumberToPolarValueConverter. The purpose of that converter is to take in a customer's balance and return a simple value which indicates if that customer either is owed money, owes money, or has no balance. If the customer owes money (i.e. the customer's balance is more than zero dollars) then it returns +1. If the customer is owed money, it returns -1. If the customer has no balance, zero is returned.

This value converter is necessary because a DataTrigger's Value property cannot express a range, it can only express a distinct value. In other words, there is no way to have the DataTrigger's Value indicate that the trigger should execute when a customer's balance is, say, any number less than zero.

Since Value cannot express a range, we can take the opposite approach and have the DataTrigger's Binding eliminate the range of values which the 'Balance' field can have. If the Binding evaluates to a small, discrete set of values (-1, 0, or +1) then the Value property can easily be used to check for those specific values.

Here is how that value converter is implemented:

[ValueConversion( typeof(object), typeof(int) )]
public class NumberToPolarValueConverter : IValueConverter
 public object Convert(
  object value,     Type targetType,
  object parameter, CultureInfo culture )
  double number = (double)System.Convert.ChangeType( value, typeof(double) );

  if( number < 0.0 )
   return -1;

  if( number == 0.0 )
   return 0;

  return +1;

 public object ConvertBack(
  object value,     Type targetType,
  object parameter, CultureInfo culture )
  throw new NotSupportedException( "ConvertBack not supported" );

External links

ADO.NET data binding in WPF

Related topics


  • April 28, 2007 – Created the article.


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


About the Author

Josh Smith
Software Developer (Senior) Cynergy Systems
United States United States
Josh creates software, for iOS and Windows.

He works at Cynergy Systems as a Senior Experience Developer.

Read his iOS Programming for .NET Developers[^] book to learn how to write iPhone and iPad apps by leveraging your existing .NET skills.

Use his Master WPF[^] app on your iPhone to sharpen your WPF skills on the go.

Check out his Advanced MVVM[^] book.

Visit his WPF blog[^] or stop by his iOS blog[^].
Follow on   Twitter

Comments and Discussions

GeneralMy vote of 5 Pin
Jonathan Schick at 12-Aug-13 9:29
memberJonathan Schick12-Aug-13 9:29 
GeneralMy vote of 5 Pin
Nyrr at 11-Feb-13 2:01
memberNyrr11-Feb-13 2:01 
GeneralMy vote of 4 Pin
Marconte at 17-Sep-12 3:11
memberMarconte17-Sep-12 3:11 
GeneralMy vote of 5 Pin
Tarun.K.S at 8-Nov-10 1:05
memberTarun.K.S8-Nov-10 1:05 
Generalthanks Pin
vegeta4ss at 27-Apr-10 7:37
membervegeta4ss27-Apr-10 7:37 
I was able to use this article to build myself a style and converter which colors objects based on the amount of time elapsed since the event was logged.

Thanks! Keep publishing wpf stuff and i'll keep reading Smile | :)
GeneralBinding to DataTable is unclear. Pin
Member 4183590 at 19-Feb-10 13:50
memberMember 418359019-Feb-10 13:50 
Generalcould you help me Pin
Sparkling_ouc at 6-Jul-09 17:34
groupSparkling_ouc6-Jul-09 17:34 
GeneralHelp me on Pin
mohammad sayedi at 5-Jul-09 1:58
membermohammad sayedi5-Jul-09 1:58 
GeneralWPF=WTF Pin
adrian73 at 21-Feb-09 5:01
memberadrian7321-Feb-09 5:01 
GeneralRe: WPF=WTF Pin
RugbyLeague at 5-Mar-09 4:41
memberRugbyLeague5-Mar-09 4:41 
GeneralRe: WPF=WTF Pin
Tibor Blazko at 20-Apr-09 22:04
memberTibor Blazko20-Apr-09 22:04 
GeneralThanks! Pin
Gary Wheeler at 3-Dec-08 6:22
memberGary Wheeler3-Dec-08 6:22 
GeneralRe: Thanks! Pin
Josh Smith at 3-Dec-08 6:24
mvpJosh Smith3-Dec-08 6:24 
GeneralNeed your suggestion Pin
Moim Hossain at 28-Jul-08 4:54
memberMoim Hossain28-Jul-08 4:54 
GeneralRe: Need your suggestion Pin
Josh Smith at 28-Jul-08 5:09
mvpJosh Smith28-Jul-08 5:09 
GeneralRe: Need your suggestion Pin
Moim Hossain at 28-Jul-08 5:22
memberMoim Hossain28-Jul-08 5:22 
QuestionHow to display multiple colors for different Cells of listview Pin
chanduin4u at 16-Jul-08 9:49
memberchanduin4u16-Jul-08 9:49 
AnswerRe: How to display multiple colors for different Cells of listview Pin
Josh Smith at 16-Jul-08 9:55
mvpJosh Smith16-Jul-08 9:55 
GeneralRe: How to display multiple colors for different Cells of listview Pin
chanduin4u at 16-Jul-08 10:00
memberchanduin4u16-Jul-08 10:00 
GeneralRe: How to display multiple colors for different Cells of listview Pin
Josh Smith at 16-Jul-08 10:03
mvpJosh Smith16-Jul-08 10:03 
GeneralRe: How to display multiple colors for different Cells of listview Pin
Tibor Blazko at 20-Apr-09 22:12
memberTibor Blazko20-Apr-09 22:12 
GeneralBrilliant [modified] Pin
Kyle Rozendo at 28-Mar-08 2:24
memberKyle Rozendo28-Mar-08 2:24 
GeneralRe: Brilliant Pin
Josh Smith at 28-Mar-08 4:22
mvpJosh Smith28-Mar-08 4:22 
GeneralGroups Pin
norm .net at 2-Oct-07 3:22
membernorm .net2-Oct-07 3:22 
GeneralRe: Groups Pin
Josh Smith at 2-Oct-07 3:35
mvpJosh Smith2-Oct-07 3:35 
GeneralRe: Groups Pin
norm .net at 2-Oct-07 4:19
membernorm .net2-Oct-07 4:19 
GeneralNice Pin
Paul Conrad at 14-Jul-07 12:01
memberPaul Conrad14-Jul-07 12:01 
GeneralCool stuff Pin
borismaletic at 5-Jul-07 2:06
memberborismaletic5-Jul-07 2:06 
QuestionThanks, good article Pin
Tomer Shamam at 19-Jun-07 2:27
memberTomer Shamam19-Jun-07 2:27 
AnswerRe: Thanks, good article Pin
Josh Smith at 19-Jun-07 3:18
mvpJosh Smith19-Jun-07 3:18 
GeneralRe: Thanks, good article Pin
Tomer Shamam at 19-Jun-07 5:49
memberTomer Shamam19-Jun-07 5:49 
GeneralRe: Thanks, good article Pin
Josh Smith at 19-Jun-07 5:55
mvpJosh Smith19-Jun-07 5:55 
AnswerRe: Thanks, good article Pin
Tomer Shamam at 14-Jan-08 23:32
memberTomer Shamam14-Jan-08 23:32 
GeneralVery nice Pin
gia nghia at 29-Apr-07 2:00
membergia nghia29-Apr-07 2:00 
GeneralRe: Very nice Pin
Josh Smith at 29-Apr-07 4:13
mvpJosh Smith29-Apr-07 4:13 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150427.1 | Last Updated 28 Apr 2007
Article Copyright 2007 by Josh Smith
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid