How to: Improve the Performance of a TreeView

If a TreeView contains many items, the amount of time it takes to load may cause a significant delay in the user interface. You can improve the load time by setting the VirtualizingStackPanel.IsVirtualizing attached property to true. The UI might also be slow to react when a user scrolls the TreeView by using the mouse wheel or dragging the thumb of a scrollbar. You can improve the performance of the TreeView when the user scrolls by setting the VirtualizingStackPanel.VirtualizationMode attached property to Recycling.


The following example creates a TreeView that sets VirtualizingStackPanel.IsVirtualizing to true and VirtualizingStackPanel.VirtualizationMode to Recycling to optimize its performance.


    <src:TreeViewData x:Key="dataItems"/>

    <HierarchicalDataTemplate DataType="{x:Type src:ItemsForTreeView}"
                              ItemsSource="{Binding Path=SecondLevelItems}">

      <!--Display the TopLevelName property in the first level.-->
      <TextBlock Text="{Binding Path=TopLevelName}"/>

      <!--Display each string in the SecondLevelItems property in
          the second level.-->
              <TextBlock Text="{Binding}"/>

      <!--Set the foreground of the items in the second level
          to Navy.-->
        <Style TargetType="TreeViewItem">
          <Setter Property="Foreground" Value="Navy"/>

  <TreeView Height="200" 
            ItemsSource="{Binding Source={StaticResource dataItems}}"

      <!--Expand each TreeViewItem in the first level and 
          set its foreground to Green.-->
      <Style TargetType="TreeViewItem">
        <Setter Property="IsExpanded" Value="True"/>
        <Setter Property="Foreground" Value="Green"/>

The following example shows the data that the previous example uses.

Public Class TreeViewData
    Inherits ObservableCollection(Of ItemsForTreeView)

    Public Sub New()
        For i As Integer = 0 To 99
            Dim item As New ItemsForTreeView()
            item.TopLevelName = "item " & i.ToString()
    End Sub
End Class

Public Class ItemsForTreeView
    Private _TopLevelName As String
    Public Property TopLevelName() As String
            Return _TopLevelName
        End Get
        Set(ByVal value As String)
            _TopLevelName = value
        End Set
    End Property
    Private level2Items As ObservableCollection(Of String)

    Public ReadOnly Property SecondLevelItems() As ObservableCollection(Of String)
            If level2Items Is Nothing Then
                level2Items = New ObservableCollection(Of String)()
            End If
            Return level2Items
        End Get
    End Property

    Public Sub New()
        For i As Integer = 0 To 9
            SecondLevelItems.Add("Second Level " & i.ToString())
    End Sub
End Class
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
© 2014 Microsoft