Click here to Skip to main content
15,881,898 members
Articles / Desktop Programming / WPF

[WPF] Highlight ListView Items

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
2 Aug 2011CPOL1 min read 24.4K   2   2
WPF highlight ListView items

I’m playing with WPF for a few days now. Trying to develop a little program, I ask myself how I can highlight some items in the listview I use, for example, showing to the project manager all the tasks that are finished or are late.

So, I imagine a simple tasklist. A task has a name and a percentage. Here is my Task class:

C#
public class Task
    {
        public string Name;
        public int Percentage;

        public static List<Tache> Get()
        {
            var tasklist = new List<Task>
                            {
                                new Task {Name = "Task 1", Percentage = 75},
                                new Task {Name = "Task 2", Percentage = 25},
                                new Task {Name = "Task 3", Percentage = 45},
                                new Task {Name = "Task 4", Percentage = 55}
                            };
            return tasklist;
        }
    }

Because this is just an example, my Get method is in my model.

First, we bind our ListView. In the MainWindow.cs, we will add this:

C#
listView.DataContext = Task.Get();

Pretty simple.

Next, we modify the XAML file to manage our data display:

XML
<ListView Name="listView" ItemsSource="{Binding}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Task" 
                    DisplayMemberBinding="{Binding Name}" />
                    <GridViewColumn Header="Percentage" 
                    DisplayMemberBinding="{Binding Percentage}" />
                </GridView>
            </ListView.View>
        </ListView>

We have defined two columns, one displaying the name of the task and the other one, the percentage realized.

And now, we are going to highlight our date. If a task has a percentage less than 50, it would be shown in red.
We use a Converter to make a link between the percentage and the color to use. Let’s create a class PercentToColorConverter inheriting from IValueConverter.

C#
public object Convert(object value, Type targetType, object parameter, 
                      System.Globalization.CultureInfo culture)
        {
            var percent = (int)System.Convert.ChangeType(value, typeof(int));

            if (percent < 50)
                return 0;

            return 1;
        }

        public object ConvertBack(object value, Type targetType, object parameter, 
                                  System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

To resume, if percentage is less than 50, the converter returns 0, else it returns 1.

We also create a style that will apply the converter to the task. At the same time, we modify the itemstyle to highlight it when the mouse is over and we modify the style of the selected element.

XML
<pre class="brush:csharp">
<Style x:Key="ListViewItemStyle" 
TargetType="{x:Type ListViewItem}">
        <Style.Resources>
            <local:PercentToColorConverter x:Key="PercentToColor" />
        </Style.Resources>

        <Style.Triggers>
            <!-- Color of the item depending on percentage value. -->
            <DataTrigger Binding="{Binding Percentage, 
             Converter={StaticResource PercentToColor}}" Value="1" >
                <Setter Property="Foreground" Value="Black" />
            </DataTrigger>

            <DataTrigger Binding="{Binding Percentage, 
             Converter={StaticResource PercentToColor}}" Value="0" >
                <Setter Property="Foreground" Value="Red" />
            </DataTrigger>

            <!-- Style for the selecting item -->
            <Trigger Property="IsSelected" Value="true">
                <Setter Property="Background" Value="Orange"/>
                <Setter Property="Foreground" Value="White"/>
            </Trigger>
            <!-- Style for the item when the mouse is over -->
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" Value="Orange" />
                <Setter Property="BorderBrush" Value="White" />
            </Trigger>
        </Style.Triggers>
    </Style>

And the end, we bind this style to our ListView:

XML
<ListView Name="listView" 
ItemContainerStyle="{StaticResource ListViewItemStyle}" 
           ItemsSource="{Binding}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Tache" 
                    DisplayMemberBinding="{Binding Name}" />
                    <GridViewColumn Header="Avancement" 
                    DisplayMemberBinding="{Binding Percentage}" />
                </GridView>
            </ListView.View>
        </ListView>

We just have to launch our application and watch the result:

License

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


Written By
Architect
France France
I'm coding in .Net since 9 years, most with ASP.Net and SharePoint and a little using WPF, MVC, Windows Phone 8 and WinRT technology.
I have learned so much reading others experience and tutorials, or tips so I try to do the same, keeping learning from others of course.
You can also find my blog here : http://sharemstips.wordpress.com/

Comments and Discussions

 
QuestionMy vote of 5 Pin
Member 27276-Oct-14 20:33
Member 27276-Oct-14 20:33 
GeneralMy vote of 5 Pin
Kashif_Imran28-May-13 23:23
Kashif_Imran28-May-13 23:23 

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.