Compartir a través de


Cómo: Mejorar el rendimiento de un control TreeView

Actualización: Julio de 2008

Si un objeto TreeView contiene gran cantidad de elementos, el tiempo que se tarda en cargarse puede producir un retraso significativo en la interfaz de usuario. Puede mejorar el tiempo de carga estableciendo la propiedad asociada VirtualizingStackPanel.IsVirtualizing en true. La interfaz de usuario también puede reaccionar con lentitud cuando un usuario se desplaza por TreeView utilizando la rueda del mouse o arrastrando el cuadro de una barra de desplazamiento. Puede mejorar el rendimiento de TreeView cuando el usuario se desplaza estableciendo la propiedad asociada VirtualizingStackPanelVirtualizationMode() en Recycling.

Ejemplo

Descripción

En el ejemplo siguiente se crea un objeto TreeView que establece la propiedad VirtualizingStackPanel.IsVirtualizing en true y la propiedad VirtualizingStackPanelVirtualizationMode() en Recycling, para optimizar su rendimiento.

Code

<StackPanel>
  <StackPanel.Resources>
    <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.-->
      <HierarchicalDataTemplate.ItemTemplate>
          <DataTemplate>
              <TextBlock Text="{Binding}"/>
          </DataTemplate>
      </HierarchicalDataTemplate.ItemTemplate>
      
      <!--Set the foreground of the items in the second level
          to Navy.-->
      <HierarchicalDataTemplate.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
          <Setter Property="Foreground" Value="Navy"/>
        </Style>
      </HierarchicalDataTemplate.ItemContainerStyle>  
    </HierarchicalDataTemplate>
  </StackPanel.Resources>

  <TreeView Height="200" ItemsSource="{Binding Source={StaticResource dataItems}}"
            VirtualizingStackPanel.IsVirtualizing="True"
            VirtualizingStackPanel.VirtualizationMode="Recycling">
    <TreeView.ItemContainerStyle>
      
      <!--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"/>
      </Style>
    </TreeView.ItemContainerStyle>
  </TreeView>
</StackPanel>

En el ejemplo siguiente se muestran los datos que se utilizan en el ejemplo anterior.

public class TreeViewData : ObservableCollection<ItemsForTreeView>
{

    public TreeViewData()
    {
        for (int i = 0; i < 100; ++i)
        {
            ItemsForTreeView item = new ItemsForTreeView();
            item.TopLevelName = "item " + i.ToString();
            Add(item);
        }
    }
}


public class ItemsForTreeView
{
    public string TopLevelName { get; set; }
    private ObservableCollection<string> level2Items;

    public ObservableCollection<string> SecondLevelItems
    {
        get 
        {
            if (level2Items == null)
            {
                level2Items = new ObservableCollection<string>();
            }
            return level2Items;
        }
    }

    public ItemsForTreeView()
    {
        for (int i = 0; i < 10; ++i)
        {
            SecondLevelItems.Add("Second Level " + i.ToString());
        }
    }
}

Vea también

Conceptos

Optimizar el rendimiento: Controles

Historial de cambios

Fecha

Historial

Motivo

Julio de 2008

Tema agregado para mostrar las nuevas características de virtualización de la interfaz de usuario y de reciclaje de contenedores.

Cambio de características de SP1.