Posted by: Zeeshan Amjad | February 14, 2010

TreeView, ListView and GridView 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. Now we are going to make the same project again, but this time using the DataConext for data binding.

Our first step is to change the static list to non static list.

  1: private List<Department> deptlist = new List<Department>();

Then we select the datacontext property of the window.

  1: DataContext = deptlist;

And then change the binding of treeview and use just the binding object here.

  1: <TreeView Name="tree" Margin="5" Grid.Row="0" Grid.Column="0"
  2:      ItemsSource="{Binding}" SelectedItemChanged="tree_SelectedItemChanged">
  3: 

Rest of the code is exactly same as previous one and we don’t have to change anything. Here is complete XAML code of the 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="{Binding}" 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: 

And 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:         private List<Department> deptlist = new List<Department>();
 24:         private List<Student> students = 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:             students.Add(new Student(10, "Alex", "Martin", 100210, "A"));
 80:             students.Add(new Student(10, "Alex", "Martin", 300101, "A"));
 81:             students.Add(new Student(10, "Alex", "Martin", 200101, "B"));
 82:             students.Add(new Student(12, "Joe", "Brown", 100101, "A"));
 83:             students.Add(new Student(12, "Joe", "Brown", 300170, "B"));
 84:             students.Add(new Student(12, "Joe", "Brown", 200203, "A"));
 85:             students.Add(new Student(16, "David", "Frank", 100212, "A"));
 86:             students.Add(new Student(16, "David", "Frank", 100218, "A"));
 87:             students.Add(new Student(16, "David", "Frank", 100213, "A"));
 88:             students.Add(new Student(16, "David", "Frank", 300101, "A"));
 89:             students.Add(new Student(16, "David", "Frank", 200100, "B"));
 90:             students.Add(new Student(18, "Patrick", "Justin", 200100, "A"));
 91:             students.Add(new Student(18, "Patrick", "Justin", 300101, "A"));
 92:             students.Add(new Student(18, "Patrick", "Justin", 100210, "A"));
 93:             students.Add(new Student(18, "Patrick", "Justin", 100211, "A"));
 94:             students.Add(new Student(25, "Ken", "White", 100210, "B"));
 95:             students.Add(new Student(25, "Ken", "White", 300101, "B"));
 96:             students.Add(new Student(25, "Ken", "White", 200101, "A"));
 97: 
 98:             DataContext = deptlist;
 99: 
100:         }
101: 
102:         private void tree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
103:         {
104:             list.Items.Clear();
105: 
106:             Subject selectedSubject = tree.SelectedItem as Subject;
107: 
108:             if (selectedSubject != null)
109:             {
110:                 int subjectID = selectedSubject.ID;
111: 
112:                 IEnumerable<Student> selectedStudents = from fn in students
113:                                                         where fn.SubjectID == subjectID
114:                                                         select fn;
115: 
116:                 foreach (Student student in selectedStudents)
117:                 {
118:                     list.Items.Add(student);
119:                 }
120:             }
121: 
122:             Department dept = tree.SelectedItem as Department;
123: 
124:             if (dept != null)
125:             {
126:                 list.Items.Add(dept);
127:             }
128:         }
129:     }
130: 
131:     public class MyTemplateSelector : DataTemplateSelector
132:     {
133:         public DataTemplate DepartmentTemplate
134:         { get; set; }
135: 
136:         public DataTemplate SubjectTemplate
137:         { get; set; }
138: 
139:         public override DataTemplate SelectTemplate(object item, DependencyObject container)
140:         {
141:             Department dept = item as Department;
142: 
143:             if (dept != null)
144:                 return DepartmentTemplate;
145: 
146:             Student student = item as Student;
147: 
148:             if (student != null)
149:                 return SubjectTemplate;
150: 
151:             return base.SelectTemplate(item, container);
152:         }
153:     }
154: 
155:     public class SubjectConverter : IValueConverter
156:     {
157:         public object Convert(object values, Type targetType,
158:             object parameter, CultureInfo culture)
159:         {
160: 
161:             TreeView selectedItem = values as TreeView;
162:             Subject subject = selectedItem.SelectedItem as Subject;
163:             return subject.Name;
164:         }
165: 
166:         public object ConvertBack(object value, Type targetType,
167:             object parameter, CultureInfo culture)
168:         {
169:             throw new NotImplementedException();
170:         }
171:     }
172: 
173:     public class Subject
174:     {
175:         public Subject(int id, String name)
176:         {
177:             ID = id;
178:             Name = name;
179:         }
180: 
181:         public int ID
182:         { get; set; }
183: 
184:         public String Name
185:         { get; set; }
186:     }
187: 
188:     public class Department
189:     {
190:         public Department()
191:         {
192:             this.Subjects = new List<Subject>();
193:         }
194: 
195:         public String Name
196:         { get; set; }
197: 
198:         public String Chairman
199:         { get; set; }
200: 
201:         public String Description
202:         { get; set; }
203: 
204:         public List<Subject> Subjects
205:         { get; set; }
206:     }
207: 
208:     public class Student
209:     {
210:         public Student()
211:         {
212:         }
213: 
214:         public Student(int id, String firstName, String lastName, int subjectID, String grade)
215:         {
216:             ID = id;
217:             FirstName = firstName;
218:             LastName = lastName;
219:             SubjectID = subjectID;
220:             Grade = grade;
221:         }
222: 
223:         public int ID
224:         { get; set; }
225: 
226:         public String FirstName
227:         { get; set; }
228: 
229:         public String LastName
230:         { get; set; }
231: 
232:         public int SubjectID
233:         { get; set; }
234: 
235:         public String Grade
236:         { get; set; }
237:     }
238: }
239: 

This is the output of the program.

Tree GridSplitter and ListView_04

Advertisements

Responses

  1. Hi,
    You have done incredible work!!
    I am new to wpf and you have helped me a lot!!!

    Can I ask you something that I am struggling?

    I have a treeview on a view eg CountryCityView
    and I have a listView on another View “CityDetailsView”

    I have tried all sorts but cannot make an example work when you select a city in a treeview which is in a view and you display the details in a listview which is in another view.

    Can you help posting an example or suggestions?

    Thanks a lot
    GB

  2. those works for me and do the job.
    I have copied and pasted the code and all works.
    However I have a requirement
    where the ListViews is in another userControl
    and the treeview with country and city is another usercontrols

    so you have 2 usercontrols

    1)Country/City
    2)CityDetails

    Selecting a city should be reflected on the other usercontrol.

    Thanks for your help

    • It shoud work exactly the same way, just set the DataContext property of user control and may have to expose one dependency property from your user control which contains treeview to give information about the selected item. I will hopefully make a sample program soon to demonstrate this.

  3. i am using /learning MVVM .
    Your site is the only one with some good examples that works for a change.

    • Thanks to like the examples.

  4. I am a novice programmer on WPF I inserted the code in this example to begin to understand how a small project, but I can not get it to work.
    The error is:
    The tag ‘SubjectConverter’ does not exist in XML namespace ‘clr-namespace: WpfApplication1’. Line 9, Position 10.
    What am I missing?
    Thanks for the help

  5. I am a novice programmer on WPF I inserted the code in this example to begin to understand how a small project, but I can not get it to work.
    The error is:
    The tag ‘SubjectConverter’ does not exist in XML namespace ‘clr-namespace: WpfApplication1′. Line 9, Position 10.
    What am I missing?
    Thanks for the help

    • Are you sure that you are using WpfApplication1 namespace? In this particular example i am using WpfTreeList my name space. If thats the case then change the xml namespace from WpfTreeList to WpfApplication1 something like this

      xmlns:local=”clr-namespace:WpfApplication1″


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: