Posted by: Zeeshan Amjad | January 7, 2010

Using 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 department with tree view and list box. But there was one problem in that program. Although that program select the data template conditionally depends on the selected item in tree view, but it still display the subject id instead of its name in list box. We can solve this problem with the help of value converter.

Here is a piece of code for converter to do this.

  1: public class SubjectConverter : IValueConverter
  2: {
  3:     public object Convert(object values, Type targetType,
  4:         object parameter, CultureInfo culture)
  5:     {
  6: 
  7:         TreeView selectedItem = values as TreeView;
  8:         Subject subject = selectedItem.SelectedItem as Subject;
  9:         return subject.Name;
 10:     }
 11: 
 12:     public object ConvertBack(object value, Type targetType,
 13:         object parameter, CultureInfo culture)
 14:     {
 15:         throw new NotImplementedException();
 16:     }
 17: }
 18: 

Now we are creating object of this in XAML.

  1: <local:SubjectConverter x:Key="subjectConverterObj"/>

Now we change the textblock binding to use this converter. Here is XAML code for this.

  1: <TextBlock Grid.Row="3" Grid.Column="1" Foreground="Black">
  2: 	<TextBlock.Text>
  3: 		<Binding Mode="OneWay" Converter="{StaticResource subjectConverterObj}">
  4: 			<Binding.ElementName>tree</Binding.ElementName>
  5: 		</Binding>
  6: 	</TextBlock.Text>
  7: </TextBlock>
  8: 

This XAML code will select the current item from the tree control and pass it into the converter.

Rest of the code is almost same as previous program. Here is 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:         <local:SubjectConverter x:Key="subjectConverterObj"/>
  8:         <DataTemplate x:Key="departmentTemplate">
  9:             <Border Margin="3" BorderBrush="Brown" Background="LightYellow" BorderThickness="2" CornerRadius="5">
 10:                 <Grid Margin="2">
 11:                     <Grid.ColumnDefinitions>
 12:                         <ColumnDefinition/>
 13:                         <ColumnDefinition/>
 14:                     </Grid.ColumnDefinitions>
 15:                     <Grid.RowDefinitions>
 16:                         <RowDefinition/>
 17:                         <RowDefinition/>
 18:                         <RowDefinition/>
 19:                     </Grid.RowDefinitions>
 20:                     <TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"
 21:                                Text="{Binding Name}" FontWeight="Bold"
 22:                                FontSize="16" Foreground="Black"
 23:                                HorizontalAlignment="Center" Margin="3"/>
 24:                     <TextBlock Grid.Row="1" Grid.Column="0" Text="Chairman"
 25:                                Foreground="Black"/>
 26:                     <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Chairman}"
 27:                                Foreground="Black"/>
 28:                     <TextBlock Grid.Row="2" Grid.Column="0" Text="Description"
 29:                                Foreground="Black"/>
 30:                     <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Description}"
 31:                                Foreground="Black"/>
 32:                 </Grid>
 33:             </Border>
 34:         </DataTemplate>
 35:         <DataTemplate x:Key="subjectTemplate">
 36:             <Border Margin="3" BorderBrush="DarkBlue" Background="AliceBlue" BorderThickness="2" CornerRadius="5">
 37:                 <Grid Margin="2">
 38:                     <Grid.ColumnDefinitions>
 39:                         <ColumnDefinition/>
 40:                         <ColumnDefinition/>
 41:                     </Grid.ColumnDefinitions>
 42:                     <Grid.RowDefinitions>
 43:                         <RowDefinition/>
 44:                         <RowDefinition/>
 45:                         <RowDefinition/>
 46:                         <RowDefinition/>
 47:                         <RowDefinition/>
 48:                     </Grid.RowDefinitions>
 49:                     <TextBlock Grid.Row="0" Grid.Column="0"
 50:                                Text="Student ID" Foreground="Black"/>
 51:                     <TextBlock Grid.Row="0" Grid.Column="1"
 52:                                Text="{Binding ID}" Foreground="Black"/>
 53:                     <TextBlock Grid.Row="1" Grid.Column="0"
 54:                                Text="First Name" Foreground="Black"/>
 55:                     <TextBlock Grid.Row="1" Grid.Column="1"
 56:                                Text="{Binding FirstName}" Foreground="Black"/>
 57:                     <TextBlock Grid.Row="2" Grid.Column="0"
 58:                                Text="Last Name" Foreground="Black"/>
 59:                     <TextBlock Grid.Row="2" Grid.Column="1"
 60:                                Text="{Binding LastName}" Foreground="Black"/>
 61:                     <TextBlock Grid.Row="3" Grid.Column="0"
 62:                                Text="Subject ID" Foreground="Black"/>
 63:                     <TextBlock Grid.Row="3" Grid.Column="1"                               
 64:                                Foreground="Black">
 65:                         <TextBlock.Text>
 66:                             <Binding Mode="OneWay" Converter="{StaticResource subjectConverterObj}">
 67:                                 <Binding.ElementName>tree</Binding.ElementName>
 68:                             </Binding>
 69:                         </TextBlock.Text>
 70:                     </TextBlock>
 71:                     <TextBlock Grid.Row="4" Grid.Column="0"
 72:                                Text="Grade" Foreground="Black"/>
 73:                     <TextBlock Grid.Row="4" Grid.Column="1"
 74:                                Text="{Binding Grade}" Foreground="Black"/>
 75:                 </Grid>
 76:             </Border>
 77:         </DataTemplate>
 78:         <local:MyTemplateSelector x:Key="myTemplateSelectorObj" 
 79:                                   DepartmentTemplate="{StaticResource departmentTemplate}"
 80:                                   SubjectTemplate="{StaticResource subjectTemplate}"/>
 81:     </Window.Resources>
 82:     <Grid Background="Wheat">
 83:         <Grid.ColumnDefinitions>
 84:             <ColumnDefinition/>
 85:             <ColumnDefinition Width="Auto"/>
 86:             <ColumnDefinition Width="2*"/>
 87:         </Grid.ColumnDefinitions>
 88:         
 89:         <TreeView Name="tree" Margin="5" Grid.Row="0" Grid.Column="0"
 90:                   ItemsSource="{x:Static local:Window1.deptList}" SelectedItemChanged="tree_SelectedItemChanged">
 91:             <TreeView.ItemTemplate>
 92:                 <HierarchicalDataTemplate ItemsSource="{Binding Path=Subjects}">
 93:                     <TextBlock Text="{Binding Name}"/>
 94:                     <HierarchicalDataTemplate.ItemTemplate>
 95:                         <DataTemplate>
 96:                             <TextBlock Text="{Binding Name}"/>
 97:                         </DataTemplate>
 98:                     </HierarchicalDataTemplate.ItemTemplate>   
 99:                 </HierarchicalDataTemplate>
100:             </TreeView.ItemTemplate>
101:         </TreeView>
102:         <GridSplitter Grid.Row="0" Grid.Column="1" Background="LightGray"
103:                       Width="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
104:         <ListBox Name="list" Margin="5" Grid.Row="0" Grid.Column="2"                  
105:                  ItemTemplateSelector="{StaticResource myTemplateSelectorObj}"
106:                  HorizontalContentAlignment="Stretch">
107:         </ListBox>
108:     </Grid>
109: </Window>
110: 

Here is 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: using System.Globalization;
 15: 
 16: namespace WpfTreeList
 17: {
 18:     /// <summary>
 19:     /// Interaction logic for Window1.xaml
 20:     /// </summary>
 21:     public partial class Window1 : Window
 22:     {
 23:         static public List<Department> deptList = new List<Department>();
 24:         static public List<Student> studentList = new List<Student>();
 25:         
 26:         public Window1()
 27:         {
 28:             InitializeComponent();
 29: 
 30:             List<Subject> sublist1 = new List<Subject>();
 31:             sublist1.Add(new Subject(100101, "Pre Calculus"));
 32:             sublist1.Add(new Subject(100210, "Calculus 1"));
 33:             sublist1.Add(new Subject(100211, "Calculus 2"));
 34:             sublist1.Add(new Subject(100212, "Calculus 3"));
 35:             sublist1.Add(new Subject(100218, "Linear Algebra"));
 36:             sublist1.Add(new Subject(100213, "Differential Equation"));
 37:             Department dept1 = new Department();
 38:             dept1.Name = "Math";
 39:             dept1.Chairman = "Bob Smit";
 40:             dept1.Description = "Applied Math Department";
 41:             dept1.Subjects = sublist1;
 42: 
 43:             deptList.Add(dept1);
 44: 
 45:             List<Subject> sublist2 = new List<Subject>();
 46:             sublist2.Add(new Subject(200100, "Business Accounting"));
 47:             sublist2.Add(new Subject(200101, "Accounting 1"));
 48:             sublist2.Add(new Subject(200102, "Accounting 2"));
 49:             sublist2.Add(new Subject(200201, "Accounting 3"));
 50:             sublist2.Add(new Subject(200201, "Accounting 4"));
 51:             sublist2.Add(new Subject(200203, "Cost Accounting"));
 52:             sublist2.Add(new Subject(200205, "Tax Accounting"));
 53:             sublist2.Add(new Subject(200214, "Auditing"));
 54:             Department dept2 = new Department();
 55:             dept2.Name = "Accounting";
 56:             dept2.Chairman = "Jon Thompson";
 57:             dept2.Description = "Accounting and Management";
 58:             dept2.Subjects = sublist2;
 59: 
 60:             deptList.Add(dept2);
 61: 
 62:             List<Subject> sublist3 = new List<Subject>();
 63:             sublist3.Add(new Subject(300101, "Introduction to CS"));
 64:             sublist3.Add(new Subject(300106, "OOP"));
 65:             sublist3.Add(new Subject(300121, "Visual Basic"));
 66:             sublist3.Add(new Subject(300170, "Security 1"));
 67:             sublist3.Add(new Subject(300201, "Computer Science"));
 68:             sublist3.Add(new Subject(300208, "C++ Programming"));
 69:             sublist3.Add(new Subject(300232, "DB Administrator"));
 70:             sublist3.Add(new Subject(300241, "Networking"));
 71:             Department dept3 = new Department();
 72:             dept3.Name = "Computer Science";
 73:             dept3.Chairman = "Chris Nathan";
 74:             dept3.Description = "Computer Engineering and Science";
 75:             dept3.Subjects = sublist3;
 76: 
 77:             deptList.Add(dept3);
 78: 
 79:             studentList.Add(new Student(10, "Alex", "Martin", 100210, "A"));
 80:             studentList.Add(new Student(10, "Alex", "Martin", 300101, "A"));
 81:             studentList.Add(new Student(10, "Alex", "Martin", 200101, "B"));
 82:             studentList.Add(new Student(12, "Joe", "Brown", 100101, "A"));
 83:             studentList.Add(new Student(12, "Joe", "Brown", 300170, "B"));
 84:             studentList.Add(new Student(12, "Joe", "Brown", 200203, "A"));
 85:             studentList.Add(new Student(16, "David", "Frank", 100212, "A"));
 86:             studentList.Add(new Student(16, "David", "Frank", 100218, "A"));
 87:             studentList.Add(new Student(16, "David", "Frank", 100213, "A"));
 88:             studentList.Add(new Student(16, "David", "Frank", 300101, "A"));
 89:             studentList.Add(new Student(16, "David", "Frank", 200100, "B"));
 90:             studentList.Add(new Student(18, "Patrick", "Justin", 200100, "A"));
 91:             studentList.Add(new Student(18, "Patrick", "Justin", 300101, "A"));
 92:             studentList.Add(new Student(18, "Patrick", "Justin", 100210, "A"));
 93:             studentList.Add(new Student(18, "Patrick", "Justin", 100211, "A"));
 94:             studentList.Add(new Student(25, "Ken", "White", 100210, "B"));
 95:             studentList.Add(new Student(25, "Ken", "White", 300101, "B"));
 96:             studentList.Add(new Student(25, "Ken", "White", 200101, "A"));
 97: 
 98:         }
 99: 
100:         private void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
101:         {
102:             list.Items.Clear();
103: 
104:             Subject selectedSubject = tree.SelectedItem as Subject;
105: 
106:             if (selectedSubject != null)
107:             {
108:                 int subjectID = selectedSubject.ID;
109: 
110:                 IEnumerable<Student> selectedStudents = from fn in studentList
111:                                                         where fn.SubjectID == subjectID
112:                                                         select fn;
113: 
114:                 foreach (Student student in selectedStudents)
115:                 {
116:                     list.Items.Add(student);
117:                 }
118:             }
119: 
120:             Department dept = tree.SelectedItem as Department;
121: 
122:             if (dept != null)
123:             {
124:                 list.Items.Add(dept);
125:             }
126:         }
127:     }
128: 
129:     public class MyTemplateSelector : DataTemplateSelector
130:     {
131:         public DataTemplate DepartmentTemplate
132:         { get; set; }
133: 
134:         public DataTemplate SubjectTemplate
135:         { get; set; }
136: 
137:         public override DataTemplate SelectTemplate(object item, DependencyObject container)
138:         {
139:             Department dept = item as Department;
140: 
141:             if (dept != null)
142:                 return DepartmentTemplate;
143: 
144:             Student student = item as Student;
145: 
146:             if (student != null)
147:                 return SubjectTemplate;
148: 
149:             return base.SelectTemplate(item, container);
150:         }
151:     }
152: 
153:     public class SubjectConverter : IValueConverter
154:     {
155:         public object Convert(object values, Type targetType,
156:             object parameter, CultureInfo culture)
157:         {
158: 
159:             TreeView selectedItem = values as TreeView;
160:             Subject subject = selectedItem.SelectedItem as Subject;
161:             return subject.Name;
162:         }
163: 
164:         public object ConvertBack(object value, Type targetType,
165:             object parameter, CultureInfo culture)
166:         {
167:             throw new NotImplementedException();
168:         }
169:     }
170: 
171:     public class Subject
172:     {
173:         public Subject(int id, String name)
174:         {
175:             ID = id;
176:             Name = name;
177:         }
178: 
179:         public int ID
180:         { get; set; }
181: 
182:         public String Name
183:         { get; set; }
184:     }
185: 
186:     public class Department
187:     {
188:         public Department()
189:         {
190:             this.Subjects = new List<Subject>();
191:         }
192: 
193:         public String Name
194:         { get; set; }
195: 
196:         public String Chairman
197:         { get; set; }
198: 
199:         public String Description
200:         { get; set; }
201: 
202:         public List<Subject> Subjects
203:         { get; set; }
204:     }
205: 
206:     public class Student
207:     {
208:         public Student()
209:         {
210:         }
211: 
212:         public Student(int id, String firstName, String lastName, int subjectID, String grade)
213:         {
214:             ID = id;
215:             FirstName = firstName;
216:             LastName = lastName;
217:             SubjectID = subjectID;
218:             Grade = grade;
219:         }
220: 
221:         public int ID
222:         { get; set; }
223: 
224:         public String FirstName
225:         { get; set; }
226: 
227:         public String LastName
228:         { get; set; }
229: 
230:         public int SubjectID
231:         { get; set; }
232: 
233:         public String Grade
234:         { get; set; }
235:     }
236: }
237: 

 

Now if we select the subject then it will display the subject name in the list box instead of subject id. Here is the output of this program.

Tree GridSplitter and ListView_04

Advertisements

Responses

  1. […] with DataContext We already saw one example of using treeview, listview and gridview here. But in that project we were using the static list of department and use that static list in XAML. […]

  2. Hi,
    Still learning a lot from your examples.
    Sorry to ask
    I have the need to display the parent node when
    selecting a child node
    EG Selecting Accounting1 should display a title
    Accounting – Accounting1

    Tried few things but cannot get the parent node

    Thanks a lot


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: