Share via


Visão geral do Controle do Servidor Web TreeView

The TreeView Web server control is used to display hierarchical data, such as a table of contents or file directory, in a tree structure.

Esse tópico contém:

  • Recursos

  • Segundo plano

  • Exemplos de código

  • Referência de Classe

Recursos

The TreeView control supports the following features:

  • Ligação de dados automática, o que permite que os nós do controle sejam ligados aos dados hierárquicos, como um documento XML.

  • Site navigation support through integration with the SiteMapDataSource control.

  • Texto de nó que pode ser exibido tanto como texto selecionável quanto como hyperlinks.

  • Aparência personalizável através de temas, imagens definidas pelo usuário, e estilos.

  • Programmatic access to the TreeView object model, which allows you to dynamically create trees, populate nodes, set properties, and so on.

  • Preenchimento de nós através de callbacks do lado do cliente para o servidor (em navegadores com suporte).

  • A capacidade de exibir uma caixa de seleção ao lado de cada nó.

Voltar ao topo

Segundo plano

The TreeView controle pode exibir vários tipos diferentes de dados: dados estático especificado declarativamente no controle, dados ligados ao controle ou dados que são adicionados à TreeView controle programaticamente, em resposta às ações do usuário.

Exibindo Dados Estáticos

You can display static data in the TreeView control by creating a collection of TreeNode elements that are children of the TreeView control.These child elements are also known as child nodes.

The following example shows the markup for a TreeView control that contains three nodes, two of which have child nodes.

<asp:TreeView ID="MyTreeView" Runat="server">
  <Nodes>
    <asp:TreeNode Value="Child1" Expanded="True" Text="1">
      <asp:TreeNode Value="Grandchild1" Text="A" />
      <asp:TreeNode Value="Grandchild2" Text="B" />
    </asp:TreeNode>
    <asp:TreeNode Value="Child2" Text="2" />
    <asp:TreeNode Value="Child3" Expanded="True" Text="3">
      <asp:TreeNode Value="Grandchild1" Text="A" />
    </asp:TreeNode>
  </Nodes>
</asp:TreeView>

Ligando Dados ao Controle TreeView

You can bind a TreeView control to a data source that supports the IHierarchicalDataSource interface, such as the XmlDataSource and SiteMapDataSource controls.Additionally, when binding data, you have complete control over which fields are populated from the data source.Para obter mais informações, consulte Ligando Dados ao Controle de Servidor Web TreeView.

Exibindo Dados Programaticamemte Usando TreeNodeCollection

Você pode popular um TreeView controle com dados programaticamente, acessando o Nodes propriedade, que retorna um TreeNodeCollection classe. TreeNodeCollection é uma coleção fortemente tipada de TreeNode objetos. Because a TreeNode object contains a property called ChildNodes that can contain TreeNode objects, the TreeNodeCollection class is a hierarchal data structure that represents all of the nodes of the TreeView control.

For an example of how to traverse the Nodes collection, see Nodes.

Tipos de Nós TreeView

The TreeView control is made up of one or more nodes.Each entry in the tree is called a node and is represented by a TreeNode object.The following table describes the three different node types.

Tipo de nó

Descrição

Raiz

Um nó que possui nenhum nó pai e um ou mais nós filho.

Pai

Um nó que possui um nó pai e um ou mais nós filho.

Folha

Um nó que não possui nenhum nó filho.

Although a typical tree has only one root node, the TreeView control allows you to add multiple root nodes to your tree structure.Isso é útil quando você deseja exibir listagens de itens sem exibir um único nó raiz principal, como em uma lista de categorias de produto.

Cada nó tem uma propriedade Text e uma propriedade Value.O valor da propriedade Text é exibida no controle TreeView, enquanto a propriedade Value é usada para armazenar quaisquer dados adicionais sobre o nó, como dados passados para o evento de postagem que está associado com o nó.

When a node of the TreeView control is clicked, it can either raise a selection event (via postback) or navigate to another page.Quando a propriedade href não está definida, clicando em um nó vai gerar um evento SelectedNodeChanged que pode ser manipulado para fornecer uma funcionalidade personalizada.Each node also has a SelectAction property that can be used to determine specific actions that happen when the node is clicked, such as expand or collapse the node.Instead of raising a selection event to navigate to a page when a node is clicked, set the href property of the node to a value other than an empty string ("").

Preenchendo Dados TreeNode por Demanda

Pode não ser prático definir a estrutura de dados estaticamente, pois os dados podem dependem de informações que são obtidas em tempo de execução.To display data dynamically, the TreeView control supports dynamic node population.When the TreeView control is configured to populate on demand, the control raises an event when a user expands the node.O manipulador de eventos recupera os dados apropriados e depois preenche o nó que o usuário clicou.To populate the TreeNode object with data on demand, set the PopulateOnDemand property of a node to true, and create a TreeNodePopulate event handler to populate the TreeNode object with data.

Preenchimento de nós do TreeView do Lado do Cliente

Any browser that has the SupportsCallback property set to true in the browser capabilities configuration file supports client-side node population.

Client-side node population enables the TreeView control to populate a node by calling the server's TreeNodePopulate event from client script instead of requiring a full postback to the server.For more information about client-side node population, see PopulateNodesFromClient.

Ativando scripts de cliente

By default, on up-level browsers, the expand-collapse functionality of a node on the TreeView control is performed using client script.O uso de script de cliente aumenta a eficiência do processamento porque o controle não tem que fazer postback para o servidor para processar a nova configuração.

Observação:

If client script is disabled in the browser or the browser does not support client script, then the TreeView control will revert to down-level mode and post back to the server each time a user clicks the node.

Postback do TreeView

By default, the TreeView control handles expand-collapse functionality on the client unless the browser does not support client script or the EnableClientScript property is set to false.If the PopulateNodesFromClient property is set to true and the browser supports client script, then the TreeView control retrieves the data from the server without posting the entire page back.

When the TreeView control is in selection mode, each time a user clicks a node, a postback to the server occurs and the SelectedNodeChanged event is raised.

Typically, you should handle postback events when the TreeView control is in selection mode or the nodes are being dynamically populated.This is because either the PopulateOnDemand or PopulateNodesFromClient property is set to true.

Using the TreeView Control with UpdatePanel Controls

UpdatePanel controls are used to update selected regions of a page instead of updating the whole page with a postback.The TreeView control can be used inside an UpdatePanel control with the following restrictions:

  • TreeView callbacks must be associated with asynchronous postbacks, or callback event validation will fail.When you set the PopulateOnDemand property of the TreeNode controls to true, callbacks are enabled.You can use one of the following approaches to ensure that TreeView callbacks work with the UpdatePanel control:

    • If the TreeView control is not inside an UpdatePanel control, disable callbacks on TreeNode controls that are not part of an asynchronous postback.To do this, set the PopulateOnDemand property to false.

    • Programmatically refresh all controls that register callbacks during the asynchronous postback.For example, you can place the TreeView control inside an UpdatePanel control.The TreeView control does not have to be in the UpdatePanel control where the asynchronous postback originates, as long as the UpdatePanel control that contains the TreeView control is refreshed.

  • You must apply styles by using a reference to a Cascading Style Sheet (CSS) class.For example, instead of setting the NodeStyle property by using a property-subproperty attribute, set the style by using the property-CssClass attribute.Similarly, when you use the NodeStyle template to set the style, use the CssClass attribute of the template.

  • The EnableClientScript property must be true (the default value).In addition, if callbacks are enabled for the TreeView control, you cannot change the EnableClientScript property between asynchronous postbacks.

For more information about using UpdatePanel controls, see Visão geral sobre controle UpdatePanel and Visão geral de renderização de página parcial.

Processamento do TreeNode

Each TreeNode object contains four UI elements, which are shown in the following image and described in the table below.

Elementos de interface do usuário de TreeNode

Item

Descrição

Expandir/recolher imagem

Uma imagem opcional que indica se o nó pode ser expandido para mostrar os nós filho.Por padrão, é um sinal de adição [+] se o nó pode ser expandido, ou um sinal de subtração [-] se o nó pode ser recolhido.

Caixa de seleção

Caixas de seleção podem ser opcionalmente ativadas, o que permite aos usuários selecionarem um nó específico.

Imagem do nó

Você pode especificar uma imagem do nó a ser exibida ao lado do texto do nó.

Texto do nó

Node text is the actual text that displays on the TreeNode object.Node text can behave like a hyperlink in navigation mode, or like a button in selection mode.

In addition to its own properties, the TreeView control supports properties of the TreeNodeStyle control for each node type.These style properties override the NodeStyle property, which applies to all node types.

The TreeView also has a NodeIndent property that specifies the indentation level for all nodes.Nodes are indented from the side on which the TreeView control is rendered.É o lado esquerdo para localidades que processam da esquerda para direita, e é o lado direito para localidades que processam da direita para esquerda.

Um nó também pode ter um estilo diferente aplicado quando ele estiver selecionada ou quando o mouse focaliza o nó.When the Selected property of a node is set to true, the SelectedNodeStyle property is applied, which overrides any unselected style properties for the selected node.When the mouse hovers over a node, the HoverNodeStyle property is applied.The following image and table describe the TreeNodeStyle properties.

Propriedades do TreeNodeStyle

Propriedade do nó

Descrição

NodeSpacing

Especifica a quantidade de espaçamento vertical entre a nó inteiro atual e nós adjacentes acima e abaixo.

VerticalPadding

Specifies the amount of space rendered on the top and bottom of the TreeNode text.

HorizontalPadding

Specifies the amount space rendered on the left and right of the TreeNode text.

ChildNodesPadding

Specifies the amount of space above and below the child nodes of the TreeNode.

ImageUrl

Specifies the path to the image that displays next to the TreeNode.

Para obter mais informações, consulte Personalizando a Aparência (Look and Feel) do Controle do Servidor Web TreeView.

Exibindo uma Caixa de Seleção ao Lado de um Nó TreeView

Another custom rendering feature of the TreeView control is its ability to render check boxes between the node text and image by using the ShowCheckBoxes property.Showing check boxes allows the user to select multiple nodes at once, which is especially useful for interfaces like a newsgroup tree, where users can select and subscribe to multiple newsgroups at once.For more information about using check boxes, see Seleção, Navegação, e Caixas de Seleção no Controle de Servidor Web TreeView.

Usando a Propriedade ExpandDepth

By default, the TreeView control displays all of the nodes of the tree expanded.You can configure the TreeView control to initially display to any depth.To do so, you can set the ExpandDepth property to a number reflecting the node level that you want to display.For example, if you set the ExpandDepth property to 2, then two levels of the node, or two child nodes, will display when the site initially renders on the client.

Exemplos de código

Eventos do Controle TreeView do Servidor Web

Personalizando a Aparência (Look and Feel) do Controle do Servidor Web TreeView

Preenchendo Nós de Árvore no Controle do Servidor Web TreeView

Ligando Dados ao Controle de Servidor Web TreeView

Seleção, Navegação, e Caixas de Seleção no Controle de Servidor Web TreeView

Usando Imagens com o Controle de Exibição de Árvore

Demonstra Passo a passo: Exibindo dados hierárquicos em um controle TreeView

Como: Adicionar ou excluir elementos TreeView nó

Voltar ao topo

Referência de Classe

A tabela seguinte lista as classes que estão relacionadas ao controle TreeView.

Membro

Descrição

TreeView

A classe principal para o controle.

Voltar ao topo

Consulte também

Conceitos

Preenchendo Nós de Árvore no Controle do Servidor Web TreeView

Personalizando a Aparência (Look and Feel) do Controle do Servidor Web TreeView

Eventos do Controle TreeView do Servidor Web

Seleção, Navegação, e Caixas de Seleção no Controle de Servidor Web TreeView