How to set a specific row color of a WPF ListView/GridView control?

Continuing the series of blog posts on WPF ListView/GridView control, today we will learn how to set the background color (more precisely, ‘the Style’) of a WPF ListView/GridView control’s row based on some specific parameter passed as the data.


You may want to give your user a proper visual by providing a different style to that specific row. Let’s discuss with a simple example.


How to change a specific row color of a WPF ListView GridView control (www.kunal-chowdhury.com)


There could be many instances when we need to color a particular row of a ListView/GridView control in our WPF application. For example, if a data model for a particular row has errors, we may need to highlight the entire row with 'Red' as the background color. For the other rows, we may want to color it to 'Green' or keep it as-is.


The below code demonstrates how to use a DataTrigger to set the background color of a WPF ListView/GridView control based on the value of the associated data model. Here you can see how we are setting the background color to red and green based on the property value of 'HasErrors' part of the associated data model:


<Style TargetType="{x:Type ListViewItem}">
        <DataTrigger Binding="{Binding HasErrors}" Value="True">
          <Setter Property="Background" Value="Red" />
        <DataTrigger Binding="{Binding HasErrors}" Value="False">
          <Setter Property="Background" Value="Green" />


You can create as many DataTrigger's as you want but make sure that, you have unique property value with which you are comparing the value to trigger the UI change. Was the post helpful? Do let me know your feedback. Also, don't forget to read my entire series on WPF ListView/GridView control and other posts. Cheers! Have a great day ahead.


Here’s the links for your easy reference: