Tuesday, June 4, 2013

Highlighting Items in a WPF ListView

This article shows how to change the color of items in a ListView, based on values in or associated with the item.


Download

Step 1: Create a WPF application and follow the following file structure.


Step 2: Add a new class in your solution named Employee.cs and update it as follows.

using System;
using System.Collections.ObjectModel;

namespace RowBold.Core
{

 //********************************************************************************************************************************
    //                                                  Class:Employee
    //********************************************************************************************************************************
    //                                     M O D I F I C A T I O N   M I L E S T O N E S
    // -------------------------------------------------------------------------------------------------------------------------------
    //  Date             |  Created By          | Description
    // --------+-------------------+--------------------------------------------------------------------------------------------------
    // June 04, 2013     | Kaushik Kuamr Mistry | This Class is used to call the Interaction logic for Employee.
    //*********************************************************************************************************************************

    /// <summary>
    /// This Class is used to call the Interaction logic for Employee.
    /// </summary>
    public class Employee
    {
        #region <<  Private Member Declarations  >>

        private ObservableCollection<Employee> lstEmployee = null;

        #endregion

        #region <<  Public Member Declarations  >>

        #endregion

        #region <<  Properties  >>

        /// <summary>
        /// Get or Set the id.
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// Get or Set the name.
        /// </summary>
        public String Name { get; set; }

        /// <summary>
        /// Get or Set the salary.
        /// </summary>
        public Decimal Salary { get; set; }

        /// <summary>
        /// Get or Set the department.
        /// </summary>
        public String Department { get; set; }

        #endregion

        #region <<  Constructors  >>

        /// <summary>
        /// The default Constructor.
        /// </summary>
        public Employee()
        {
            this.lstEmployee = new ObservableCollection<Employee>();
        }

        #endregion

        #region <<  Private Method Declarations  >>

        #endregion

        #region <<  Public Method Declarations  >>

        /// <summary>
        /// This method is used to initialize the list of employee.
        /// </summary>
        /// <returns></returns>
        /// <Developer>Kaushik Kuamr Mistry</Developer>
        /// <DateCreated>June 04, 2013</DateCreated>
        /// <ModifiedBy>...</ModifiedBy>
        /// <ModifiedDate>...</ModifiedDate>
        public ObservableCollection<Employee> GetEmployees()
        {
            try
            {
                this.lstEmployee.Add(new Employee { Id = 1, Name = "Kaushik Mistry", Salary = 35000M, Department = "Software Development" });
                this.lstEmployee.Add(new Employee { Id = 2, Name = "Amit Sharma", Salary = 29000M, Department = "Software Development" });
                this.lstEmployee.Add(new Employee { Id = 3, Name = "Akanksha Bhardwaj", Salary = 40000M, Department = "Software Development" });
                this.lstEmployee.Add(new Employee { Id = 4, Name = "Rohit Kaushik", Salary = 35700M, Department = "Software Development" });
                this.lstEmployee.Add(new Employee { Id = 5, Name = "Priyank Gupta", Salary = 30000M, Department = "Designer" });
                this.lstEmployee.Add(new Employee { Id = 6, Name = "Prashant Yadav", Salary = 20000M, Department = "Quality Assurance" });
                this.lstEmployee.Add(new Employee { Id = 7, Name = "Pushp Singh", Salary = 25000M, Department = "Software Development" });
                this.lstEmployee.Add(new Employee { Id = 8, Name = "Subodh Arya", Salary = 35400M, Department = "Software Development" });
                this.lstEmployee.Add(new Employee { Id = 9, Name = "Ajay Shukla", Salary = 45000M, Department = "Software Development" });
                this.lstEmployee.Add(new Employee { Id = 10, Name = "Abhay Kumar", Salary = 37000M, Department = "Designer" });
                this.lstEmployee.Add(new Employee { Id = 11, Name = "Abhimanyu Kheria", Salary = 35000M, Department = "Quality Assurance" });
            }
            catch (Exception)
            {
                throw;
            }
            return this.lstEmployee;
        }

        #endregion
    }
}

****************************************************************************

Step 3: Add a another new class in your solution named TextToFontWeight.cs and update it as follows.

using System;
using System.Windows.Data;

namespace RowBold.Common
{

    //********************************************************************************************************************************
    //                                                  Class:TextToFontWeight
    //********************************************************************************************************************************
    //                                     M O D I F I C A T I O N   M I L E S T O N E S
    // -------------------------------------------------------------------------------------------------------------------------------
    //  Date             |  Created By          | Description 
    // --------+-------------------+--------------------------------------------------------------------------------------------------
    // June 04, 2013     | Kaushik Kuamr Mistry | This Class is used to call the Interaction logic for TextToFontWeight. 
    //*********************************************************************************************************************************

    /// <summary>
    /// This Class is used to call the Interaction logic for TextToFontWeight.
    /// </summary>
    public class TextToFontWeight : IValueConverter
    {
        #region <<  Private Member Declarations  >>

        #endregion

        #region <<  Public Member Declarations  >>

        #endregion

        #region <<  Properties  >>

        #endregion

        #region <<  Constructors  >>

        /// <summary>
        /// The default Constructor.
        /// </summary>
        public TextToFontWeight()
        {
        }

        #endregion

        #region <<  Private Method Declarations  >>

        #endregion

        #region <<  Public Method Declarations  >>

        object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Decimal salary = Convert.ToDecimal(value);
            if (salary < 30000M)
                return true;
            else
               return false;
        }

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

        #endregion

    }
}

****************************************************************************

Step 4: Update the xaml of MainWindow as follows.

<Window x:Class="RowBold.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:global="clr-namespace:RowBold.Common"
        Title="MainWindow"
        Height="325"
        Width="580"
        Loaded="Window_Loaded">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <ListView Name="lstEmployee"
                      Grid.Row="0"
                      Grid.ColumnSpan="2"
                      ScrollViewer.VerticalScrollBarVisibility="Auto"
                      ScrollViewer.HorizontalScrollBarVisibility="Auto"
                      SelectionMode="Multiple"
                      VerticalAlignment="Top"
                      HorizontalAlignment="Left">
            <ListView.Resources>
                <global:TextToFontWeight x:Key="ttfw"/>
            </ListView.Resources>
            <ListView.ItemContainerStyle>
                <Style TargetType="{x:Type ListViewItem}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Salary, Converter={StaticResource ttfw}}" Value="true" >
                            <Setter Property="FontWeight" Value="Bold" />
                            <Setter Property="Background" Value="LightYellow" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </ListView.ItemContainerStyle>
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}" Width="100"/>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="150"/>
                    <GridViewColumn Header="Salary" DisplayMemberBinding="{Binding Salary}" Width="150" />
                    <GridViewColumn Header="Department" DisplayMemberBinding="{Binding Department}" Width="150" />
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

using System;
using System.Windows;
using RowBold.Core;

namespace RowBold
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region <<  Windows Events  >>

        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow" /> class.
        /// </summary>
        /// <Developer>Kaushik Kuamr Mistry</Developer>
        /// <DateCreated>June 04, 2013</DateCreated>
        /// <ModifiedBy>...</ModifiedBy>
        /// <ModifiedDate>...</ModifiedDate>
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Handels the Loaded event of Window.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <Developer>Kaushik Kuamr Mistry</Developer>
        /// <DateCreated>June 04, 2013</DateCreated>
        /// <ModifiedBy>...</ModifiedBy>
        /// <ModifiedDate>...</ModifiedDate>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                Employee employee=new Employee();
                this.lstEmployee.ItemsSource = employee.GetEmployees();
            }
            catch (Exception)
            {
                throw;
            }
        }

        #endregion
    }
}