We have already seen how to apply data template conditionally. Now we are going to apply it on tree view and list view sample. We are going to create two data template to display department and students information. Here is a piece of code to define two data templates.
Here is a department and subjects data template
1: <DataTemplate x:Key="departmentTemplate">2: <Border Margin="3" BorderBrush="Brown" Background="LightYellow" BorderThickness="2" CornerRadius="5">3: <Grid Margin="2">4: <Grid.ColumnDefinitions>5: <ColumnDefinition/>6: <ColumnDefinition/>7: </Grid.ColumnDefinitions>8: <Grid.RowDefinitions>9: <RowDefinition/>10: <RowDefinition/>11: <RowDefinition/>12: </Grid.RowDefinitions>13: <TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"14: Text="{Binding Name}" FontWeight="Bold"15: FontSize="16" Foreground="Black"16: HorizontalAlignment="Center" Margin="3"/>17: <TextBlock Grid.Row="1" Grid.Column="0" Text="Chairman"18: Foreground="Black"/>19: <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Chairman}"20: Foreground="Black"/>21: <TextBlock Grid.Row="2" Grid.Column="0" Text="Description"22: Foreground="Black"/>23: <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Description}"24: Foreground="Black"/>25: </Grid>26: </Border>27: </DataTemplate>28: <DataTemplate x:Key="subjectTemplate">29: <Border Margin="3" BorderBrush="DarkBlue" Background="AliceBlue" BorderThickness="2" CornerRadius="5">30: <Grid Margin="2">31: <Grid.ColumnDefinitions>32: <ColumnDefinition/>33: <ColumnDefinition/>34: </Grid.ColumnDefinitions>35: <Grid.RowDefinitions>36: <RowDefinition/>37: <RowDefinition/>38: <RowDefinition/>39: <RowDefinition/>40: <RowDefinition/>41: </Grid.RowDefinitions>42: <TextBlock Grid.Row="0" Grid.Column="0"43: Text="Student ID" Foreground="Black"/>44: <TextBlock Grid.Row="0" Grid.Column="1"45: Text="{Binding ID}" Foreground="Black"/>46: <TextBlock Grid.Row="1" Grid.Column="0"47: Text="First Name" Foreground="Black"/>48: <TextBlock Grid.Row="1" Grid.Column="1"49: Text="{Binding FirstName}" Foreground="Black"/>50: <TextBlock Grid.Row="2" Grid.Column="0"51: Text="Last Name" Foreground="Black"/>52: <TextBlock Grid.Row="2" Grid.Column="1"53: Text="{Binding LastName}" Foreground="Black"/>54: <TextBlock Grid.Row="3" Grid.Column="0"55: Text="Subject ID" Foreground="Black"/>56: <TextBlock Grid.Row="3" Grid.Column="1"57: Text="{Binding SubjectID}" Foreground="Black"/>58: <TextBlock Grid.Row="4" Grid.Column="0"59: Text="Grade" Foreground="Black"/>60: <TextBlock Grid.Row="4" Grid.Column="1"61: Text="{Binding Grade}" Foreground="Black"/>62: </Grid>63: </Border>64: </DataTemplate>65:Now we are inherit class from DataTemplateSelector. Here is a code of it.
1: public class MyTemplateSelector : DataTemplateSelector2: {3: public DataTemplate DepartmentTemplate4: { get; set; }5:6: public DataTemplate SubjectTemplate7: { get; set; }8:9: public override DataTemplate SelectTemplate(object item, DependencyObject container)10: {11: Department dept = item as Department;12:13: if (dept != null)14: return DepartmentTemplate;15:16: Student student = item as Student;17:18: if (student != null)19: return SubjectTemplate;20:21: return base.SelectTemplate(item, container);22: }23: }24:Now we are using this class in XAML.
1: <local:MyTemplateSelector x:Key="myTemplateSelectorObj"2: DepartmentTemplate="{StaticResource departmentTemplate}"3: SubjectTemplate="{StaticResource subjectTemplate}"/>4:Next step is using this my template in our list box.
1: <ListBox Name="list" Margin="5" Grid.Row="0" Grid.Column="2"2: ItemTemplateSelector="{StaticResource myTemplateSelectorObj}"3: HorizontalContentAlignment="Stretch">4: </ListBox>5:Now we are writing a handler for tree view item change.
1: private void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)2: {3: list.Items.Clear();4:5: Subject selectedSubject = tree.SelectedItem as Subject;6:7: if (selectedSubject != null)8: {9: int subjectID = selectedSubject.ID;10:11: IEnumerable<Student> selectedStudents = from fn in studentList12: where fn.SubjectID == subjectID13: select fn;14:15: foreach (Student student in selectedStudents)16: {17: list.Items.Add(student);18: }19: }20:21: Department dept = tree.SelectedItem as Department;22:23: if (dept != null)24: {25: list.Items.Add(dept);26: }27: }28:It is important to note that, although the tree view store information about department and subject, but select template method of our MyTemplateSelector class checks Department and Subjects. Because we are inserting Department and Subjects object in the list box.
Here is a complete XAML code of this program.
1: <Window x:Class="WpfTreeList.Window1"2: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3: xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"4: xmlns:local="clr-namespace:WpfTreeList"5: Title="Tree, GridSplitter and ListView" Height="400" Width="600">6: <Window.Resources>7: <DataTemplate x:Key="departmentTemplate">8: <Border Margin="3" BorderBrush="Brown" Background="LightYellow" BorderThickness="2" CornerRadius="5">9: <Grid Margin="2">10: <Grid.ColumnDefinitions>11: <ColumnDefinition/>12: <ColumnDefinition/>13: </Grid.ColumnDefinitions>14: <Grid.RowDefinitions>15: <RowDefinition/>16: <RowDefinition/>17: <RowDefinition/>18: </Grid.RowDefinitions>19: <TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"20: Text="{Binding Name}" FontWeight="Bold"21: FontSize="16" Foreground="Black"22: HorizontalAlignment="Center" Margin="3"/>23: <TextBlock Grid.Row="1" Grid.Column="0" Text="Chairman"24: Foreground="Black"/>25: <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Chairman}"26: Foreground="Black"/>27: <TextBlock Grid.Row="2" Grid.Column="0" Text="Description"28: Foreground="Black"/>29: <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Description}"30: Foreground="Black"/>31: </Grid>32: </Border>33: </DataTemplate>34: <DataTemplate x:Key="subjectTemplate">35: <Border Margin="3" BorderBrush="DarkBlue" Background="AliceBlue" BorderThickness="2" CornerRadius="5">36: <Grid Margin="2">37: <Grid.ColumnDefinitions>38: <ColumnDefinition/>39: <ColumnDefinition/>40: </Grid.ColumnDefinitions>41: <Grid.RowDefinitions>42: <RowDefinition/>43: <RowDefinition/>44: <RowDefinition/>45: <RowDefinition/>46: <RowDefinition/>47: </Grid.RowDefinitions>48: <TextBlock Grid.Row="0" Grid.Column="0"49: Text="Student ID" Foreground="Black"/>50: <TextBlock Grid.Row="0" Grid.Column="1"51: Text="{Binding ID}" Foreground="Black"/>52: <TextBlock Grid.Row="1" Grid.Column="0"53: Text="First Name" Foreground="Black"/>54: <TextBlock Grid.Row="1" Grid.Column="1"55: Text="{Binding FirstName}" Foreground="Black"/>56: <TextBlock Grid.Row="2" Grid.Column="0"57: Text="Last Name" Foreground="Black"/>58: <TextBlock Grid.Row="2" Grid.Column="1"59: Text="{Binding LastName}" Foreground="Black"/>60: <TextBlock Grid.Row="3" Grid.Column="0"61: Text="Subject ID" Foreground="Black"/>62: <TextBlock Grid.Row="3" Grid.Column="1"63: Text="{Binding SubjectID}" Foreground="Black"/>64: <TextBlock Grid.Row="4" Grid.Column="0"65: Text="Grade" Foreground="Black"/>66: <TextBlock Grid.Row="4" Grid.Column="1"67: Text="{Binding Grade}" Foreground="Black"/>68: </Grid>69: </Border>70: </DataTemplate>71: <local:MyTemplateSelector x:Key="myTemplateSelectorObj"72: DepartmentTemplate="{StaticResource departmentTemplate}"73: SubjectTemplate="{StaticResource subjectTemplate}"/>74: </Window.Resources>75: <Grid Background="Wheat">76: <Grid.ColumnDefinitions>77: <ColumnDefinition/>78: <ColumnDefinition Width="Auto"/>79: <ColumnDefinition Width="2*"/>80: </Grid.ColumnDefinitions>81:82: <TreeView Name="tree" Margin="5" Grid.Row="0" Grid.Column="0"83: ItemsSource="{x:Static local:Window1.deptList}" SelectedItemChanged="tree_SelectedItemChanged">84: <TreeView.ItemTemplate>85: <HierarchicalDataTemplate ItemsSource="{Binding Path=Subjects}">86: <TextBlock Text="{Binding Name}"/>87: <HierarchicalDataTemplate.ItemTemplate>88: <DataTemplate>89: <TextBlock Text="{Binding Name}"/>90: </DataTemplate>91: </HierarchicalDataTemplate.ItemTemplate>92: </HierarchicalDataTemplate>93: </TreeView.ItemTemplate>94: </TreeView>95: <GridSplitter Grid.Row="0" Grid.Column="1" Background="LightGray"96: Width="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>97: <ListBox Name="list" Margin="5" Grid.Row="0" Grid.Column="2"98: ItemTemplateSelector="{StaticResource myTemplateSelectorObj}"99: HorizontalContentAlignment="Stretch">100: </ListBox>101: </Grid>102: </Window>103:And here is a complete C# code of the program.
1: using System;2: using System.Collections.Generic;3: using System.Linq;4: using System.Text;5: using System.Windows;6: using System.Windows.Controls;7: using System.Windows.Data;8: using System.Windows.Documents;9: using System.Windows.Input;10: using System.Windows.Media;11: using System.Windows.Media.Imaging;12: using System.Windows.Navigation;13: using System.Windows.Shapes;14:15: namespace WpfTreeList16: {17: /// <summary>18: /// Interaction logic for Window1.xaml19: /// </summary>20: public partial class Window1 : Window21: {22: static public List<Department> deptList = new List<Department>();23: private List<Student> studentList = new List<Student>();24:25: public Window1()26: {27: InitializeComponent();28:29: List<Subject> sublist1 = new List<Subject>();30: sublist1.Add(new Subject(100101, "Pre Calculus"));31: sublist1.Add(new Subject(100210, "Calculus 1"));32: sublist1.Add(new Subject(100211, "Calculus 2"));33: sublist1.Add(new Subject(100212, "Calculus 3"));34: sublist1.Add(new Subject(100218, "Linear Algebra"));35: sublist1.Add(new Subject(100213, "Differential Equation"));36: Department dept1 = new Department();37: dept1.Name = "Math";38: dept1.Chairman = "Bob Smit";39: dept1.Description = "Applied Math Department";40: dept1.Subjects = sublist1;41:42: deptList.Add(dept1);43:44: List<Subject> sublist2 = new List<Subject>();45: sublist2.Add(new Subject(200100, "Business Accounting"));46: sublist2.Add(new Subject(200101, "Accounting 1"));47: sublist2.Add(new Subject(200102, "Accounting 2"));48: sublist2.Add(new Subject(200201, "Accounting 3"));49: sublist2.Add(new Subject(200201, "Accounting 4"));50: sublist2.Add(new Subject(200203, "Cost Accounting"));51: sublist2.Add(new Subject(200205, "Tax Accounting"));52: sublist2.Add(new Subject(200214, "Auditing"));53: Department dept2 = new Department();54: dept2.Name = "Accounting";55: dept2.Chairman = "Jon Thompson";56: dept2.Description = "Accounting and Management";57: dept2.Subjects = sublist2;58:59: deptList.Add(dept2);60:61: List<Subject> sublist3 = new List<Subject>();62: sublist3.Add(new Subject(300101, "Introduction to CS"));63: sublist3.Add(new Subject(300106, "OOP"));64: sublist3.Add(new Subject(300121, "Visual Basic"));65: sublist3.Add(new Subject(300170, "Security 1"));66: sublist3.Add(new Subject(300201, "Computer Science"));67: sublist3.Add(new Subject(300208, "C++ Programming"));68: sublist3.Add(new Subject(300232, "DB Administrator"));69: sublist3.Add(new Subject(300241, "Networking"));70: Department dept3 = new Department();71: dept3.Name = "Computer Science";72: dept3.Chairman = "Chris Nathan";73: dept3.Description = "Computer Engineering and Science";74: dept3.Subjects = sublist3;75:76: deptList.Add(dept3);77:78: studentList.Add(new Student(10, "Alex", "Martin", 100210, "A"));79: studentList.Add(new Student(10, "Alex", "Martin", 300101, "A"));80: studentList.Add(new Student(10, "Alex", "Martin", 200101, "B"));81: studentList.Add(new Student(12, "Joe", "Brown", 100101, "A"));82: studentList.Add(new Student(12, "Joe", "Brown", 300170, "B"));83: studentList.Add(new Student(12, "Joe", "Brown", 200203, "A"));84: studentList.Add(new Student(16, "David", "Frank", 100212, "A"));85: studentList.Add(new Student(16, "David", "Frank", 100218, "A"));86: studentList.Add(new Student(16, "David", "Frank", 100213, "A"));87: studentList.Add(new Student(16, "David", "Frank", 300101, "A"));88: studentList.Add(new Student(16, "David", "Frank", 200100, "B"));89: studentList.Add(new Student(18, "Patrick", "Justin", 200100, "A"));90: studentList.Add(new Student(18, "Patrick", "Justin", 300101, "A"));91: studentList.Add(new Student(18, "Patrick", "Justin", 100210, "A"));92: studentList.Add(new Student(18, "Patrick", "Justin", 100211, "A"));93: studentList.Add(new Student(25, "Ken", "White", 100210, "B"));94: studentList.Add(new Student(25, "Ken", "White", 300101, "B"));95: studentList.Add(new Student(25, "Ken", "White", 200101, "A"));96:97: }98:99: private void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)100: {101: list.Items.Clear();102:103: Subject selectedSubject = tree.SelectedItem as Subject;104:105: if (selectedSubject != null)106: {107: int subjectID = selectedSubject.ID;108:109: IEnumerable<Student> selectedStudents = from fn in studentList110: where fn.SubjectID == subjectID111: select fn;112:113: foreach (Student student in selectedStudents)114: {115: list.Items.Add(student);116: }117: }118:119: Department dept = tree.SelectedItem as Department;120:121: if (dept != null)122: {123: list.Items.Add(dept);124: }125: }126: }127:128: public class MyTemplateSelector : DataTemplateSelector129: {130: public DataTemplate DepartmentTemplate131: { get; set; }132:133: public DataTemplate SubjectTemplate134: { get; set; }135:136: public override DataTemplate SelectTemplate(object item, DependencyObject container)137: {138: Department dept = item as Department;139:140: if (dept != null)141: return DepartmentTemplate;142:143: Student student = item as Student;144:145: if (student != null)146: return SubjectTemplate;147:148: return base.SelectTemplate(item, container);149: }150: }151:152: public class Subject153: {154: public Subject(int id, String name)155: {156: ID = id;157: Name = name;158: }159:160: public int ID161: { get; set; }162:163: public String Name164: { get; set; }165: }166:167: public class Department168: {169: public Department()170: {171: this.Subjects = new List<Subject>();172: }173:174: public String Name175: { get; set; }176:177: public String Chairman178: { get; set; }179:180: public String Description181: { get; set; }182:183: public List<Subject> Subjects184: { get; set; }185: }186:187: public class Student188: {189: public Student()190: {191: }192:193: public Student(int id, String firstName, String lastName, int subjectID, String grade)194: {195: ID = id;196: FirstName = firstName;197: LastName = lastName;198: SubjectID = subjectID;199: Grade = grade;200: }201:202: public int ID203: { get; set; }204:205: public String FirstName206: { get; set; }207:208: public String LastName209: { get; set; }210:211: public int SubjectID212: { get; set; }213:214: public String Grade215: { get; set; }216: }217: }218:This will be the output of the program when we selects the department name from the tree view.
And this is the output when we select subjects from the tree view.


[...] TreeView, GridSplitter, ListBox with Value Converter We have already make one program to display the department name, subjects offer by the department and students enrolled in that [...]
By: Using TreeView, GridSplitter, ListBox with Value Converter « Zeeshan Amjad's WPF Blog on January 22, 2010
at 11:31 pm
[...] saw one example of applying data template conditionally here. Now we are going to apply the data template conditionally on data grid. The main difference [...]
By: Apply conditional data template in Data Grid « Zeeshan Amjad's WPF Blog on August 23, 2010
at 12:08 pm