Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

WPF Wonders: Using DataTemplates : Page 3

WPF data templates let you determine the pieces a repetitive control uses to display its items. Learn some unique and interesting ways to use data templates for displaying the items in ListBoxes, ComboBoxes, and ListViews.


advertisement

ComboBoxes with Data Templates

Figure 4. Catchy ComboBox: ComboBoxes use DataTemplates just as ListBoxes do.
ComboBoxes are basically ListBoxes in a tight real estate market, so it should come as no surprise that DataTemplates work exactly the same way with them. The CoursesComboBox program shown in Figure 4 is the same as the previous program except it uses a ComboBox instead of a ListBox.

TreeViews with Data Templates

ListViews and ComboBoxes use a DataTemplate to figure out how to display each item. All of the items are the same, so a single template can easily do the trick.

The TreeView control is a bit more ambitious. The items that a TreeView displays can have sub-items that may be from a different class. For example, in an organizational chart, top-level nodes might represent the CEO and Board of Directors. The next level might hold the CFO, COO, and other CXOs, in addition to various presidents of this and that. The next level down might hold vice presidents, followed by directors, and so on down the tree.



If you had to, you could probably build a single mega-class to hold information on all of these different kinds of positions and the organizations they control, but the ListView is more flexible than that. It lets you use different kinds of objects for different nodes in the tree.

This means the ListView's HierchicalDataTemplate must do more than the DataTemplate used by a ListBox or ComboBox. The HierchicalDataTemplate must do two things for each type of node the control may encounter:

  1. The HierchicalDataTemplate must indicate how to display a node of this type. This is similar to the way a ListBox's DataTemplate works.
  2. The HierchicalDataTemplate must tell the control how to descend from that node type farther down the tree. For example, if the TreeView encounters a President node, you might want it to follow that object's VicePresidents collection that holds the VPs reporting to this President.

If you keep these goals in mind, the syntax actually isn't all that bad.

Returning now to the pet store example, suppose the owners want to be able to look up courses divided by department (Cats, Dogs, Rodents, Reptiles, and Fish) or category (Training, Choosing, or Preparing). All of the departments and categories are grouped into terms (Spring 2010, Summer 2010, and so forth).

The CoursesTreeView example program models this situation with Term, Department, Category, and Course classes. In addition to standard data properties that hold things like names and images, the classes provide list properties that hold references to the objects that should appear below them in the "hierarchy." For example, the Term class has a Departments property that returns a List of Department that gives all of the Departments. Similarly, the Department class has a Courses property that returns a List of Course that gives the Courses offered within that department.

Figure 5. Terrific Trees: The TreeView control's Hierarchical Data Template lets it navigate through complex data.

In addition to its Departments property, the Term class has a Categories property that lists the available Category objects. Because a Department and Category may share the same class ("Dog Training, 1" is in the Dogs Department and the Training Category), the result isn't really a tree. Fortunately, the TreeView doesn't care as long as its HierarchicalDataTemplate can tell it how to move through the data.

The CoursesTreeView example program shown in Figure 5 displays the exact same data in two different TreeView controls. The one on the left uses its HierarchicalDataTemplate to move through the data by Department, while the one on the right moves through the data by Category.

The following code fragment shows how the TreeView on the left navigates Term objects. The HierarchicalDataTemplates for the other classes are omitted.

<TreeView Name="trvByDepartment" Grid.Row="1" Grid.Column="0" Margin="5" Background="LightGreen"> <TreeView.Resources> <!-- Use when we visit a Term node --> <HierarchicalDataTemplate DataType="{x:Type local:Term}" ItemsSource="{Binding Path=Departments}"> <Grid Width="200" Margin="5"> <Rectangle Fill="LightBlue" RadiusX="10" RadiusY="10"> <Rectangle.BitmapEffect> <BevelBitmapEffect EdgeProfile="BulgedUp"/> </Rectangle.BitmapEffect> </Rectangle> <TextBlock Text="{Binding Path=TermName}" Margin="10" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock.BitmapEffect> <DropShadowBitmapEffect/> </TextBlock.BitmapEffect> </TextBlock> </Grid> </HierarchicalDataTemplate> ... Other HierarchicalDataTemplates for other classes ... </TreeView.Resources> </TreeView>

The TreeView's Resources section holds the HierarchicalDataTemplates that determine how the control behaves. The HierarchicalDataTemplate's DataType attribute gives the kind of node that the template handles. The template in the preceding code is for the local:Term class. The namespace alias "local" represents the code-behind and is defined at the top of the XAML file with the following line. (CoursesTreeView is the program's namespace.)

xmlns:local="clr-namespace:CoursesTreeView"

The HierarchicalDataTemplate's ItemsSource attribute tells the ListView what objects to follow to move deeper into the data hierarchy. In this example, the template tells the control that when it sees a Term node, it should follow that node's Departments property to generate the next level in the tree.

The content inside the HierarchicalDataTemplate tells how the control should display the object that it is currently visiting. This works much as the DataTemplate objects for ListBoxes and ComboBoxes do, except the HierarchicalDataTemplate applies only to nodes of a certain type. That means the ListView can use completely different display templates for each type of object that it visits. In this example, the template's content displays the rounded rectangles that say "Spring 2010" in Figure 5.

The example program's other HierarchicalDataTemplates are similar, only the details are changed so they can display other types of nodes in different ways.

Give Data Templates a Try

Data templates, and particularly the HierarchicalDataTemplate, seem a bit daunting at first. When you give them a try, though, you'll probably find that they're not so bad. They let you apply WPF techniques that you already know to display each of the objects in a series of items in remarkably expressive ways.

Download the example programs and experiment with them a bit to see what you can make them do. Then try applying these techniques to programs of your own.

Note that this article glosses over a few data-binding issues such as how to attach data to controls and how to bind items other than the simple properties used here. For more information on data binding, search the online help or look for my WPF book coming in a few months.



Rod Stephens is a consultant and author who has written more than a dozen books and two hundred magazine articles, mostly about Visual Basic. During his career he has worked on an eclectic assortment of applications for repair dispatch, fuel tax tracking, professional football training, wastewater treatment, geographic mapping, and ticket sales. His VB Helper web site receives more than 7 million hits per month and provides three newsletters and thousands of tips, tricks, and examples for Visual Basic programmers.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap