- WPF TreeView Control Introduction
- WPF TreeView Headers
- WPF TreeView Data Binding
- WPF TreeView Multiple Templates
- WPF TreeView Selection/Expansion State
- WPF TreeView Lazy Loading
The TreeView is the best control for displaying hierarchical data with nodes because it has nodes that the user can expand and collapse. TreeViews items are stacked vertically, just like the Menu. The programmer will fill the Tree with TreeViewItems. TreeViewItem’s Header property contains the current item and its Items collection contains subitems, which are expected to be TreeViewItems.
Always use TreeView to explicitly wrap items in a TreeView.
Below is a screenshot of a very simple TreeView example. There are 3 identical TrreViews each in their own row of a Grid. By default the TreeView is collapsed as you see in the top one.
Below is the XAML code. There is no code-behind.
<Window x:Class="TreeViewSimple.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:TreeViewSimple" mc:Ignorable="d" WindowStartupLocation="CenterScreen" Title="TreeViewSimple" Height="250" Width="400"> <Grid Margin="6"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <TreeView Grid.Row="0"> <TreeViewItem Header="Desktop"> <TreeViewItem Header="Computer"></TreeViewItem> <TreeViewItem Header="Recycle Bin"></TreeViewItem> <TreeViewItem Header="Control Panel"> <TreeViewItem Header="Programs"></TreeViewItem> <TreeViewItem Header="Security"></TreeViewItem> <TreeViewItem Header="UserAccounts"></TreeViewItem> </TreeViewItem> </TreeViewItem> </TreeView> <TreeView Grid.Row="1"> <TreeViewItem Header="Desktop"> <TreeViewItem Header="Computer"></TreeViewItem> <TreeViewItem Header="Recycle Bin"></TreeViewItem> <TreeViewItem Header="Control Panel"> <TreeViewItem Header="Programs"></TreeViewItem> <TreeViewItem Header="Security"></TreeViewItem> <TreeViewItem Header="UserAccounts"></TreeViewItem> </TreeViewItem> </TreeViewItem> </TreeView> <TreeView Grid.Row="2"> <TreeViewItem Header="Desktop"> <TreeViewItem Header="Computer"></TreeViewItem> <TreeViewItem Header="Recycle Bin"></TreeViewItem> <TreeViewItem Header="Control Panel"> <TreeViewItem Header="Programs"></TreeViewItem> <TreeViewItem Header="Security"></TreeViewItem> <TreeViewItem Header="UserAccounts"></TreeViewItem> </TreeViewItem> </TreeViewItem> </TreeView> </Grid> </Window>
If you want a node to be expanded, you can use the IsExpanded property and set it to True. If you use the code below, the top TreeView will look like the middle TreeView in the screenshot.
<TreeViewItem Header="Desktop" IsExpanded="True">