Visão geral e configuração da grade de árvore do Blazor
A Grade de Árvore Blazor é um componente de interface do usuário que combina a funcionalidade de uma grade de dados (tabela) com uma exibição de árvore, permitindo que os dados hierárquicos sejam facilmente exibidos em um formato tabular. Ao contrário de uma grade regular, uma grade de árvore permite que as linhas se expandam e recolham, revelando linhas filho aninhadas nas linhas pai, tornando-a útil para representar dados estruturados, como exploradores de arquivos, organogramas, tarefas de projeto ou categorias de produtos.
Ignite UI for Blazor Tree Grid é usado para exibir e manipular dados hierárquicos ou simples com facilidade. Vincule rapidamente seus dados com muito pouco código ou use uma variedade de eventos para personalizar diferentes comportamentos. Este componente fornece um rico conjunto de recursos, como seleção de dados, filtragem de estilo do Excel, classificação, paginação, modelagem e movimentação de colunas. A exibição de dados tabulares nunca foi tão fácil e bonita graças à grade de árvore de interface do usuário baseada em tabela de materiais.
Blazor Tree Grid Example
Neste exemplo, você pode ver como os usuários podem manipular dados hierárquicos ou simples. Incluímos opções de filtragem e classificação, fixação e ocultação, seleção de linhas, exportação para excel e csv.
Example
Getting Started with Ignite UI for Blazor Tree Grid
Dependencies
Começar a usar nossa biblioteca Blazor Grid e o Blazor Tree Grid em particular é o primeiro passo para criar aplicativos poderosos e ricos em dados que exibem informações hierárquicas de maneira clara e interativa. A Grade de Árvore Blazor permite que você apresente estruturas de dados pai-filho em um formato tabular familiar, completo com recursos como expansão de linha, classificação, filtragem, edição e virtualização para alto desempenho com grandes conjuntos de dados.
To get started with the Blazor tree grid, first you need to install the IgniteUI.Blazor package.
Consulte estes tópicos sobre como adicionar o pacote IgniteUI.Blazor:
Você também precisa incluir o seguinte link CSS no arquivo index.html do seu aplicativo para fornecer os estilos necessários para a grade de árvore:
<link href="_content/IgniteUI.Blazor/themes/grid/light/bootstrap.css" rel="stylesheet" />
Depois, você pode começar a implementar o controle adicionando os seguintes namespaces:
@using IgniteUI.Blazor.Controls
Component Modules
// in Program.cs file
builder.Services.AddIgniteUIBlazor(typeof(IgbTreeGridModule));
Usage
A grade de árvore compartilha muitos recursos com a grade, mas também adiciona a capacidade de exibir seus dados hierarquicamente. Para conseguir isso, a grade de árvore nos fornece algumas maneiras de definir as relações entre nossos objetos de dados - usando uma coleção filho para cada objeto de dados ou usando chaves primárias e estrangeiras para cada objeto de dados.
Tree Cells
Independentemente de qual opção é usada para criar a hierarquia da grade de árvore (coleção filho ou chaves primárias e estrangeiras), as linhas da grade de árvore são construídas de dois tipos de células:
GridCell- Ordinary cell that contains a value.TreeGridCell- Tree cell that contains a value, an expand/collapse indicator and an indentation div element, which is based on the level of the cell's row. The level of a row component can be accessed through thelevelproperty of its innertreeRow.
[!Note] Each row can have only one tree cell, but it can have multiple (or none) ordinary cells.
Initial Expansion Depth
Initially the tree grid will expand all node levels and show them. This behavior can be configured using the ExpansionDepth property. By default its value is Infinity which means all node levels will be expanded. You may control the initial expansion depth by setting this property to a numeric value. For example 0 will show only root level nodes, 1 will show root level nodes and their child nodes and so on.
Child Collection
Quando estamos usando a opção de coleção filho, cada objeto de dados contém uma coleção filho, que é preenchida com itens do mesmo tipo que o objeto de dados pai. Dessa forma, cada registro na grade da árvore terá uma referência direta a qualquer um de seus filhos. Nesse caso, a propriedade de dados de nossa grade de árvore que contém a fonte de dados original será uma coleção definida hierarquicamente.
Para este exemplo, vamos usar a seguinte estrutura de coleção:
public class EmployeesNestedDataItem
{
public double ID { get; set; }
public double Age { get; set; }
public double Salary { get; set; }
public double Productivity { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string HireDate { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public List<EmployeesItem> Employees { get; set; }
}
public class EmployeesItem
{
public double Age { get; set; }
public double Salary { get; set; }
public double Productivity { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Phone { get; set; }
public string HireDate { get; set; }
public double ID { get; set; }
public string Name { get; set; }
public string Title { get; set; }
}
Now let's start by importing our Data collection and binding it to our tree grid.
<IgbTreeGrid
AutoGenerate="false"
ChildDataKey="Employees"
Data="EmployeesNestedData"
Name="treeGrid"
@ref="treeGrid">
<IgbColumn Field="Name" DataType="GridColumnDataType.String"></IgbColumn>
<IgbColumn Field="HireDate" DataType="GridColumnDataType.Date"></IgbColumn>
<IgbColumn Field="Age" DataType="GridColumnDataType.Number"> </IgbColumn>
</IgbTreeGrid>
In order for the tree grid to build the hierarchy, we will have to set its ChildDataKey property to the name of the child collection that is used in each of our data objects. In our case that will be the Employees collection.
In addition, we can disable the automatic column generation and define them manually by matching them to the actual properties of our data objects. (The Employees collection will be automatically used for the hierarchy, so there is no need to include it in the columns' definitions.)
We can now enable the row selection and paging features of the tree grid by using the RowSelection and add the IgbPaginator element.
We can also enable the summaries, the filtering, sorting, editing, moving and resizing features for each of our columns.
<IgbTreeGrid AutoGenerate="false"
ChildDataKey="Employees"
Data="EmployeesNestedData"
RowSelection="GridSelectionMode.Multiple"
AllowFiltering=true
Moving=true
Name="treeGrid"
@ref="treeGrid">
<IgbColumn Field="Name" DataType="GridColumnDataType.String" Sortable=true Editable=true Resizable=true HasSummary=true></IgbColumn>
<IgbColumn Field="HireDate" DataType="GridColumnDataType.Date" Sortable=true Editable=true Resizable=true HasSummary=true></IgbColumn>
<IgbColumn Field="Age" DataType="GridColumnDataType.Number" Sortable=true Editable=true Resizable=true HasSummary=true> </IgbColumn>
<IgbPaginator></IgbPaginator>
</IgbTreeGrid>
Finally, we can enable the toolbar of our tree grid, along with the column hiding, column pinning and exporting features by using the IgbGridToolbar, IgbGridToolbarHiding, IgbGridToolbarPinning and IgbGridToolbarExporter respectively.
<IgbTreeGrid AutoGenerate="false"
ChildDataKey="Employees"
Data="EmployeesNestedData"
RowSelection="GridSelectionMode.Multiple"
AllowFiltering=true
Moving=true
Name="treeGrid"
@ref="treeGrid">
<IgbColumn Field="Name" DataType="GridColumnDataType.String" Sortable=true Editable=true Resizable=true HasSummary=true></IgbColumn>
<IgbColumn Field="HireDate" DataType="GridColumnDataType.Date" Sortable=true Editable=true Resizable=true></IgbColumn>
<IgbColumn Field="Age" DataType="GridColumnDataType.Number" Sortable=true Editable=true Resizable=true > </IgbColumn>
<IgbPaginator></IgbPaginator>
<IgbGridToolbar>
<IgbGridToolbarTitle> Employees </IgbGridToolbarTitle>
<IgbGridToolbarActions>
<IgbGridPinningActions></IgbGridPinningActions>
<IgbGridToolbarHiding></IgbGridToolbarHiding>
<IgbGridToolbarExporter></IgbGridToolbarExporter>
</IgbGridToolbarActions>
</IgbGridToolbar>
</IgbTreeGrid>
Você pode ver o resultado do código acima no início deste artigo na seção Exemplo de grade de árvore.
Primary and Foreign keys
When we are using the primary and foreign keys option, every data object contains a primary key and a foreign key. The primary key is the unique identifier of the current data object and the foreign key is the unique identifier of its parent. In this case the data property of our tree grid that contains the original data source will be a flat collection.
public class EmployeesFlatDataItem
{
public double Age { get; set; }
public string HireDate { get; set; }
public double ID { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public bool OnPTO { get; set; }
public double ParentID { get; set; }
public string Title { get; set; }
}
In the sample data above, all records have an ID, a ParentID and some additional properties like Name, JobTitle and Age. As mentioned previously, the ID of the records must be unique as it will be our PrimaryKey. The ParentID contains the ID of the parent node and could be set as a ForeignKey. If a row has a ParentID that does not match any row in the tree grid, then that means this row is a root row.
The parent-child relation is configured using the tree grid's PrimaryKey and ForeignKey properties.
Aqui está o modelo do componente que demonstra como configurar a grade de árvore para exibir os dados definidos na coleção plana acima:
<IgbTreeGrid AutoGenerate="false"
PrimaryKey="ID"
ForeignKey="ParentID"
Data="EmployeesFlatDataItem"
Name="treeGrid">
<IgbColumn Field="Name" DataType="GridColumnDataType.String"></IgbColumn>
<IgbColumn Field="JobTitle" DataType="GridColumnDataType.String"></IgbColumn>
<IgbColumn Field="Age" DataType="GridColumnDataType.Number"></IgbColumn>
</IgbTreeGrid>
Além disso, habilitaremos o recurso de seleção de linha da grade de árvore usando a propriedade rowSelection e também os recursos de filtragem, classificação, edição, movimentação e redimensionamento para cada uma de nossas colunas.
<IgbTreeGrid AutoGenerate="false"
PrimaryKey="ID"
ForeignKey="ParentID"
Data="EmployeesFlatDataItem"
RowSelection="GridSelectionMode.Multiple"
AllowFiltering=true
Moving=true
Name="treeGrid"
@ref="treeGrid">
<IgbColumn Field="Name" DataType="GridColumnDataType.String" Sortable=true Editable=true Resizable=true></IgbColumn>
<IgbColumn Field="JobTitle" DataType="GridColumnDataType.String" Sortable=true Editable=true Resizable=true></IgbColumn>
<IgbColumn Field="Age" DataType="GridColumnDataType.Number" Sortable=true Editable=true Resizable=true> </IgbColumn>
</IgbTreeGrid>
E aqui está o resultado final:
Persistence and Integration
O recuo da célula da grade de árvore persiste em outros recursos de grade de árvore, como filtragem, classificação e paginação.
- When
Sortingis applied on a column, the data rows get sorted by levels. This means that the root level rows will be sorted independently from their respective children. Their respective children collections will each be sorted independently as well and so on. - The first column (the one that has a
VisibleIndexof 0) is always the tree column. - The column that ends up with a
VisibleIndexof 0 after operations like column pinning, column hiding and column moving becomes the tree column. - As planilhas do Excel exportadas refletem a hierarquia agrupando os registros à medida que são agrupados na própria grade de árvore. Todos os estados expandidos de registros também seriam persistidos e refletidos.
- Ao exportar para CSV, os níveis e estados expandidos são ignorados e todos os dados são exportados como simples.
Blazor Tree Grid Styling Configuration
Além dos temas predefinidos, a grade pode ser ainda mais personalizada ao definir algumas das propriedades CSS disponíveis. Caso você queira alterar algumas das cores, precisa definir uma classe para a grade primeiro:
<IgbTreeGrid Class="tree-grid">
Em seguida, defina as propriedades CSS relacionadas para essa classe:
.tree-grid {
--ig-grid-header-background: #494949;
--ig-grid-header-text-color: #FFF;
--ig-grid-expand-icon-color: #FFCD0F;
--ig-grid-expand-icon-hover-color: #E0B710;
--ig-grid-row-hover-background: #F8E495;
}
API References
Additional Resources
Nossa comunidade é ativa e sempre acolhedora para novas ideias.