Show / Hide Table of Contents

Практическое руководство. Повышение производительности элемента управления TreeView

Если TreeView содержит много элементов, количество времени, затрачиваемого на загрузку может привести к значительной задержке в пользовательском интерфейсе. Можно сократить время загрузки, задав VirtualizingStackPanel.IsVirtualizing вложенное свойство, чтобы true. Пользовательский Интерфейс также может медленно реагировать при прокрутке TreeView , используя колесико мыши или перетаскивания ползунка полосы прокрутки. Можно повысить производительность TreeView при прокрутке, задав VirtualizingStackPanel.VirtualizationMode вложенное свойство, чтобы VirtualizationMode.Recycling.

Пример

Описание

В следующем примере создается TreeView , задает VirtualizingStackPanel.IsVirtualizing присоединенное свойство в значение true и VirtualizingStackPanel.VirtualizationMode вложенное свойство, чтобы VirtualizationMode.Recycling для оптимизации производительности.

Код

<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>

В следующем примере показано данные в предыдущем примере.

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
        {
            level2Items ??= new ObservableCollection<string>();
            return level2Items;
        }
    }

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

См. также

  • Элементы управления
Back to top Неофициальная документация по .NET на русском языке. Лицензия: CC-BY 4.0. Основано на документации по .NET с Microsoft Docs
Generated by DocFX