TreeView

Introduction

The TreeView control is a scrollable view which can contain a hierarchy of TreeViewItems. The TreeView is conceptually similar to the ListBox control, but allows items to be embedded within other items.

Layout Requirements

The TreeView control requires:

  • An object named VerticalScrollBarInstance which implements ScrollBarBehavior (is a ScrollBar)
  • An object named InnerPanelInstance of any type (typically a Container)
  • An object named ClipContainerInstance of any type (typically a Container with ClipsChildren set to true)

The requirements for the TreeView are identical to the requirements for the ScrollViewer and ListBox controls.

Items

The Items property represents the top-level data displayed in the TreeView. Items can contain regular types (such as strings, ints, or classes representing data in your game such as car data in a racing game) or TreeViewItem instances.

When an object is added to the Items collection the TreeView will automatically update its visuals to display the newly-added object. If the newly-added object is a regular (non TreeViewItem) type, then the TreeView will construct a new TreeViewItem internally. If the newly-added object is already a TreeViewItem, then the TreeView will display the TreeViewItem as-is.

Note that at the time of this writing, adding TreeViewItems is required to create a hierarchy.

Items.Add

The following code shows how to create a hierarchy of objects. Notice that the code constructs a TreeViewItem, then uses the reference to add additional objects as sub-items of the TreeViewItem.

Note that the TreeView’s Items property only contains the top-level item. In the example above, the treeView.Items property only contains a single entry – Monster. The specific monster types are contained in the Items property of the parent TreeViewItem.

Customizing TreeViewItems

For information on creating a custom TreeViewItem, see the TreeViewItem documentation.

Selection

SelectedObject

Returns the selected object, or null if nothing is selected. This returns the object as it was originally added to the TreeView or its parent TreeViewItem.

SelectedItem

SelectedItem returns the selected TreeViewItem, or null if one isn’t selected. This property may return a nested item. Note that even if a non-TreeViewItem object is added to a TreeView, the SelectedItem for that added object will still be a TreeView.

SelectNextVisible/SelectPreviousVisible

Selects the next or previous visible object sequentially. This may select an object that above or below the hierarchy. This can be used to implement selecting items using a keyboard (up or down arrows) or game pad (up or down on dpad or analog stick).

If no object is selected, these methods will throw an InvalidOperationException.

The following example code could be used to move the selection using the arrow keys: