Effective Data Representation in Windows Presentation Foundation (WPF) using Data Triggers

Posted by: Mahesh Sabnis , on 8/23/2010, in Category WPF
Views: 39290
Abstract: Recently in one of the team discussions, we were talking about effective data representation using WPF and the excellent DataGrid control provided to make this possible. We discussed about displaying data in a WPF DataGrid and change the style of each DataGridRow based upon the data in DataGridCell. I thought of writing an article to help those who have a similar requirement.
Recently in one of the team discussions, we were talking about effective data representation using WPF and the excellent DataGrid control provided to make this possible. We discussed about displaying data in a WPF DataGrid and change the style of each DataGridRow based upon the data in DataGridCell. I thought of writing an article to help those who have a similar requirement.
In this article, I have taken an example of Employee Information application, where each employee batch is in different color, depending upon the designation. To achieve a customized UI in WPF, we have been provided a mechanism of styling WPF element based upon data bound with the element (DataTrigger) or actions taken on the element e.g. MouseOver etc (PropertyTrigger).
Applying Styles on WPF DataGrid Cells based Upon Data Bound
 
Step 1: Open VS2010 and create an WPF application, name it as ‘WPF_DataGrid_PropertyTriggers’.
Step 2: In this project, add a new class file and name it as ‘DataFiles’. In this class file add following two classes.
C#
using System.Collections.ObjectModel;
 
Namespace WPF_DataGrid_PropertyTriggers
{
    Public Class Employee
    {
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public string DeptName { get; set; }
        public string Designation { get; set; }
        public int Experience { get; set; }
        public int Salary { get; set; }
    }
 
    public class EmployeeCollection : ObservableCollection<Employee>
    {
            Public EmployeeCollection()
        {
            Add(new Employee() { EmpNo = 101, EmpName = "Ramesh", DeptName = "IT", Designation = "Manager", Experience = 15, Salary = 300000 });
            Add(new Employee() { EmpNo = 102, EmpName = "Ajay", DeptName = "Accts", Designation = "Clerk", Experience = 12, Salary = 200000 });
            Add(new Employee() { EmpNo = 103, EmpName = "Atul", DeptName = "Tech", Designation = "Supervisor", Experience = 10, Salary = 400000 });
            Add(new Employee() { EmpNo = 104, EmpName = "Narayan", DeptName = "Hrd", Designation = "Supervisor", Experience = 14, Salary = 400000 });
            Add(new Employee() { EmpNo = 105, EmpName = "Baban", DeptName = "Hrd", Designation = "Manager", Experience = 18, Salary = 300000 });
            Add(new Employee() { EmpNo = 106, EmpName = "Mandar", DeptName = "IT", Designation = "Operator", Experience = 12, Salary = 200000 });
            Add(new Employee() { EmpNo = 107, EmpName = "Suraj", DeptName = "Accts", Designation = "Operator", Experience = 22, Salary = 200000 });
            Add(new Employee() { EmpNo = 108, EmpName = "Chaitanya", DeptName = "Tech", Designation = "Supervisor", Experience = 13, Salary = 400000 });
            Add(new Employee() { EmpNo = 109, EmpName = "Anand", DeptName = "Tech", Designation = "Manager", Experience = 16, Salary = 300000 });
            Add(new Employee() { EmpNo = 110, EmpName = "Kapil", DeptName = "Hrd", Designation = "Clerk", Experience = 10, Salary = 200000 });
        }
    }
}
 
VB.NET (Converted Code)
Imports System.Collections.ObjectModel
 
Private Property WPF_DataGrid_PropertyTriggers() As [Namespace]
      Public Class Employee
            public Integer EmpNo {get;set;}
            public String EmpName {get;set;}
            public String DeptName {get;set;}
            public String Designation {get;set;}
            public Integer Experience {get;set;}
            public Integer Salary {get;set;}
 
      public class EmployeeCollection : ObservableCollection(Of Employee)
                  Public EmployeeCollection()
                  Add(New Employee() With {.EmpNo = 101, .EmpName = "Ramesh", .DeptName = "IT", .Designation = "Manager", .Experience = 15, .Salary = 300000})
                  Add(New Employee() With {.EmpNo = 102, .EmpName = "Ajay", .DeptName = "Accts", .Designation = "Clerk", .Experience = 12, .Salary = 200000})
                  Add(New Employee() With {.EmpNo = 103, .EmpName = "Atul", .DeptName = "Tech", .Designation = "Supervisor", .Experience = 10, .Salary = 400000})
                  Add(New Employee() With {.EmpNo = 104, .EmpName = "Narayan", .DeptName = "Hrd", .Designation = "Supervisor", .Experience = 14, .Salary = 400000})
                  Add(New Employee() With {.EmpNo = 105, .EmpName = "Baban", .DeptName = "Hrd", .Designation = "Manager", .Experience = 18, .Salary = 300000})
                  Add(New Employee() With {.EmpNo = 106, .EmpName = "Mandar", .DeptName = "IT", .Designation = "Operator", .Experience = 12, .Salary = 200000})
                  Add(New Employee() With {.EmpNo = 107, .EmpName = "Suraj", .DeptName = "Accts", .Designation = "Operator", .Experience = 22, .Salary = 200000})
                  Add(New Employee() With {.EmpNo = 108, .EmpName = "Chaitanya", .DeptName = "Tech", .Designation = "Supervisor", .Experience = 13, .Salary = 400000})
                  Add(New Employee() With {.EmpNo = 109, .EmpName = "Anand", .DeptName = "Tech", .Designation = "Manager", .Experience = 16, .Salary = 300000})
                  Add(New Employee() With {.EmpNo = 110, .EmpName = "Kapil", .DeptName = "Hrd", .Designation = "Clerk", .Experience = 10, .Salary = 200000})
End Property
The above two classes represents data definition (Employee) and data storage (EmployeeCollection).
Step 3: Open MainWindow.Xaml and write the following XAML code:
<Window x:Class="WPF_DataGrid_PropertyTriggers.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:src="clr-namespace:WPF_DataGrid_PropertyTriggers"
        Title="MainWindow" Height="382" Width="892">
    <Window.Resources>
        <src:EmployeeCollection x:Key="EmpCol"></src:EmployeeCollection>
        <Style TargetType="{x:Type DataGridCell}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Designation}" Value="Manager">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding Designation}" Value="Clerk">
                    <Setter Property="Background" Value="Yellow"></Setter>
               </DataTrigger>
                <DataTrigger Binding="{Binding Designation}" Value="Supervisor">
                    <Setter Property="Background" Value="Chocolate"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding Designation}" Value="Operator">
                    <Setter Property="Background" Value="Magenta"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid DataContext="{Binding Source={StaticResource EmpCol}}">
        <DataGrid AutoGenerateColumns="True" Height="272" HorizontalAlignment="Left" Margin="43,48,0,0"
                  Name="dgEmp" VerticalAlignment="Top" Width="652" ItemsSource="{Binding}"
                   ColumnWidth="*"/>
        <TextBlock Height="45" HorizontalAlignment="Left" Margin="132,0,0,0"
                   Name="textBlock1" Text="Employee Infoemation System"
                   VerticalAlignment="Top" Width="467" OpacityMask="#FF930000"
                   FontStyle="Oblique" FontWeight="ExtraBold" FontSize="26" TextWrapping="WrapWithOverflow"
                   TextTrimming="CharacterEllipsis" />
        <StackPanel Height="250" HorizontalAlignment="Left" Margin="717,52,0,0" Name="stackPanel1"
                    VerticalAlignment="Top" Width="125">
            <StackPanel Orientation="Horizontal">
                <TextBlock Width="80" Text="Manager" FontSize="15"></TextBlock>
                <Rectangle Fill="Red" Width="44"></Rectangle>
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock Width="80" Text="Clerk" FontSize="15"></TextBlock>
                <Rectangle Fill="Yellow" Width="44"></Rectangle>
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock Width="80" Text="Supervisor" FontSize="15"></TextBlock>
                <Rectangle Fill="Chocolate" Width="44"></Rectangle>
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock Width="80" Text="Operator" FontSize="15"></TextBlock>
                <Rectangle Fill="Magenta" Width="44"></Rectangle>
            </StackPanel>
        </StackPanel>
        <TextBlock Height="35" HorizontalAlignment="Left" Margin="717,11,0,0" Name="textBlock2" Text="Legend" VerticalAlignment="Top" Width="123" FontSize="20" />
    </Grid>
</Window>
 
In the above XAML code windows resources section, we declare an instance of the EmployeeCollection class. Style is defined for the DataGridCell target type. This means that when the condition of the DataTrigger matches with the DataGridCell based upon the ‘Designation’ property from the data source, the background property of the DataGridRow will change to the color specified into the ‘Setter’ of the Style. This is as simple as it sounds.
Step 4: Run the application and the following result will be displayed:
EmployeeInformationSystem
The entire source code of this article can be downloaded over here
What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook