Share via


Visão Geral da Tabela

Table é um elemento de nível de bloco que suporta a apresentação baseada em grade do conteúdo de documento de fluxo. A flexibilidade deste elemento o torna muito útil, mas também mais difícil de entender e utilizar corretamente.

Este tópico contém as seguintes seções.

  • Básico de Tabela

  • Como uma Tabela Difere de uma Grade?

  • Estrutura Básica de Tabela

  • Continência de Tabela

  • Agrupamentos de Linha

  • Precedência de Renderização de Fundo

  • Extrapolando Linhas ou Colunas

  • Construindo uma Tabela com Código

  • Tópicos relacionados

Básico de Tabela

Como uma Tabela Difere de uma Grade?

Table e Grid compartilham funcionalidade comum, mas cada um é mais adequado para diferentes cenários. Um Table é projetado para utilizar em conteúdo de fluxo (veja Flow Document Overview) para mais informações obre conteúdo de fluxo). Grades são utilizadas em formulários (basicamente em qualquer lugar fora de conteúdo de fluxo). Dentro de um FlowDocument, Table suporta comportamentos de conteúdo de fluxo como paginação, refluxo de coluna, e seleção de conteúdo enquanto um Grid não. Um Grid por outro lado é melhor utilizado fora de um FlowDocument por muitas razões incluindo Grid acrescenta elementos com base num índice de linha e coluna, Table não. O elemento Grid permite conteúdo filho em camadas, permitindo que mais de um elemento exista em uma única célula. Table não suporta camadas. Elementos filho de um Gridpode ser absolutamente posicionado em relação à área de seus limites de "célula". Table não oferece suporte a esse recurso. Finalmente, um Grid requer menos recursos que um Table, então considere utilizar um Grid para melhorar o desempenho.

Estrutura Básica de Tabela

Table Fornece uma apresentação baseada em grade formado por colunas (representadas por TableColumn elementos) e (representadas por linhas TableRow elementos). TableColumn elementos não host conteúdo; eles simplesmente definem colunas e as características de colunas. TableRow elementos devem ser hospedados em um TableRowGroup elemento, que define um agrupamento de linhas da tabela. TableCell elementos, que contêm o conteúdo real a serem apresentados pela tabela, devem ser hospedados em um TableRow elemento. TableCell só pode conter elementos que derivam de Block. Elementos filhos válidos de um TableCell incluem:

ObservaçãoObservação:

Elementos TableCell podem não hospedar diretamente conteúdo textual. Para mais informações sobre as regras de continência de elementos de conteúdo de fluxo como TableCell, veja Flow Document Overview.

ObservaçãoObservação:

Table é semelhante ao elemento Grid mas tem mais capacidades e, portanto, requer mais overhead de recursos.

O exemplo a seguir define uma tabela simples 2 x 3 com XAML.

<!-- 
  Table is a Block element, and as such must be hosted in a container
  for Block elements.  FlowDocument provides such a container. 
-->
<FlowDocument>
  <Table>
    <!-- 
      This table has 3 columns, each described by a TableColumn 
      element nested in a Table.Columns collection element. 
    -->
    <Table.Columns>
      <TableColumn />
      <TableColumn />
      <TableColumn />
    </Table.Columns>
    <!-- 
      This table includes a single TableRowGroup which hosts 2 rows,
      each described by a TableRow element.
    -->
    <TableRowGroup>
      <!--
        Each of the 2 TableRow elements hosts 3 cells, described by
        TableCell elements.
      -->
      <TableRow>
        <TableCell>
          <!-- 
            TableCell elements may only host elements derived from Block.
            In this example, Paragaph elements serve as the ultimate content
            containers for the cells in this table.
          -->
          <Paragraph>Cell at Row 1 Column 1</Paragraph>
        </TableCell>
        <TableCell>
          <Paragraph>Cell at Row 1 Column 2</Paragraph>
        </TableCell>
        <TableCell>
          <Paragraph>Cell at Row 1 Column 3</Paragraph>
        </TableCell>
      </TableRow>
      <TableRow>
        <TableCell>
          <Paragraph>Cell at Row 2 Column 1</Paragraph>
        </TableCell>
        <TableCell>
          <Paragraph>Cell at Row 2 Column 2</Paragraph>
        </TableCell>
        <TableCell>
          <Paragraph>Cell at Row 2 Column 3</Paragraph>
        </TableCell>
      </TableRow>
    </TableRowGroup>
  </Table>

</FlowDocument>

A figura a seguir mostra como o exemplo é renderizado.

Captura de tela: Processar básico Zoom, Para Cima e Ampliar

Continência de Tabela

Table deriva do elemento Block, e adere às regras comuns para elementos de nível Block. Um elemento Table pode estar contido em qualquer um dos seguintes elementos:

Agrupamentos de Linha

O elemento TableRowGroup fornece uma forma de agrupar arbitrariamente linhas de uma tabela; cada linha em uma tabela deve pertencer a um agrupamento de linha. Linhas em um grupo de linhas com frequência uma intenção comum, e pode ser estilizada como um grupo. Um uso comum de agrupamentos de linha é separar linhas de propósito especial, tais como linhas de título, cabeçalho e rodapé, do conteúdo principal contido na tabela.

O exemplo a seguir utiliza XAML para definir uma tabela com linhas estilizadas de cabeçalho e rodapé.






<Table>
  <Table.Resources>
    <!-- Style for header/footer rows. -->
    <Style x:Key="headerFooterRowStyle" TargetType="{x:Type TableRowGroup}">
      <Setter Property="FontWeight" Value="DemiBold"/>
      <Setter Property="FontSize" Value="16"/>
      <Setter Property="Background" Value="LightGray"/>
    </Style>
    <!-- Style for data rows. -->
    <Style x:Key="dataRowStyle" TargetType="{x:Type TableRowGroup}">
      <Setter Property="FontSize" Value="12"/>
      <Setter Property="FontStyle" Value="Italic"/>
    </Style>
  </Table.Resources>
  <Table.Columns>
    <TableColumn/> <TableColumn/> <TableColumn/> <TableColumn/>
  </Table.Columns>
  <!-- This TableRowGroup hosts a header row for the table. -->
  <TableRowGroup Style="{StaticResource headerFooterRowStyle}">
    <TableRow>
      <TableCell/>
      <TableCell><Paragraph>Gizmos</Paragraph></TableCell>
      <TableCell><Paragraph>Thingamajigs</Paragraph></TableCell>
      <TableCell><Paragraph>Doohickies</Paragraph></TableCell>
    </TableRow>
  </TableRowGroup>
  <!-- This TableRowGroup hosts the main data rows for the table. -->
  <TableRowGroup Style="{StaticResource dataRowStyle}">
    <TableRow>
      <TableCell><Paragraph Foreground="Blue">Blue</Paragraph></TableCell>
      <TableCell><Paragraph>1</Paragraph></TableCell>
      <TableCell><Paragraph>2</Paragraph></TableCell>
      <TableCell><Paragraph>3</Paragraph> </TableCell>
    </TableRow>
    <TableRow>
      <TableCell><Paragraph Foreground="Red">Red</Paragraph></TableCell>
      <TableCell><Paragraph>1</Paragraph></TableCell>
      <TableCell><Paragraph>2</Paragraph></TableCell>
      <TableCell><Paragraph>3</Paragraph></TableCell>
    </TableRow>
    <TableRow>
      <TableCell><Paragraph Foreground="Green">Green</Paragraph></TableCell>
      <TableCell><Paragraph>1</Paragraph></TableCell>
      <TableCell><Paragraph>2</Paragraph></TableCell>
      <TableCell><Paragraph>3</Paragraph></TableCell>
    </TableRow>
  </TableRowGroup>
  <!-- This TableRowGroup hosts a footer row for the table. -->
  <TableRowGroup Style="{StaticResource headerFooterRowStyle}">
    <TableRow>
      <TableCell><Paragraph>Totals</Paragraph></TableCell>
      <TableCell><Paragraph>3</Paragraph></TableCell>
      <TableCell><Paragraph>6</Paragraph></TableCell>
      <TableCell>
        <Table></Table>
      </TableCell>
    </TableRow>
  </TableRowGroup>
</Table>

A figura a seguir mostra como o exemplo é renderizado.

Captura de tela: Zoom, Para Cima e Ampliar grupos de linha

Precedência de Renderização de Fundo

Elementos de tabela renderizam na seguinte ordem (z-order do menor para o maior). Esta ordem não pode ser alterada. Por exemplo, não há propriedade "Z-order" para esses elementos que você pode utilizar para sobrepor essa ordem estabelecida.

  1. Table

  2. TableColumn

  3. TableRowGroup

  4. TableRow

  5. TableCell

Considere o exemplo a seguir, que define cores de fundo para cada um dos elementos em uma tabela.

<Table Background="Yellow">
  <Table.Columns>
    <TableColumn/>
    <TableColumn Background="LightGreen"/>
    <TableColumn/>
  </Table.Columns>
  <TableRowGroup>
    <TableRow>
      <TableCell/><TableCell/><TableCell/>
    </TableRow>
  </TableRowGroup>
  <TableRowGroup Background="Tan">
    <TableRow>
      <TableCell/><TableCell/><TableCell/>
    </TableRow>
    <TableRow Background="LightBlue">
      <TableCell/><TableCell Background="Purple"/><TableCell/>
    </TableRow>
    <TableRow>
      <TableCell/><TableCell/><TableCell/>
    </TableRow>
  </TableRowGroup>
  <TableRowGroup>
    <TableRow>
      <TableCell/><TableCell/><TableCell/>
    </TableRow>
  </TableRowGroup>
</Table>

A figura a seguir mostra como o exemplo é renderizado (exibindo apenas as cores de fundo).

Captura de tela: Ordem-z de tabela

Extrapolando Linhas ou Colunas

Células de tabela podem ser configuradas para extrapolar múltiplas linhas ou colunas utilizando os atributos RowSpan ou ColumnSpan, respectivamente.

Considere o exemplo a seguir, no qual uma célula ocupa três colunas.


<Table>
  <Table.Columns>
    <TableColumn/>
    <TableColumn/>
    <TableColumn/>
  </Table.Columns>
  <TableRowGroup>
    <TableRow>
      <TableCell ColumnSpan="3" Background="Cyan">
        <Paragraph>This cell spans all three columns.</Paragraph>
      </TableCell>
    </TableRow>
    <TableRow>
      <TableCell Background="LightGray"><Paragraph>Cell 1</Paragraph></TableCell>
      <TableCell Background="LightGray"><Paragraph>Cell 2</Paragraph></TableCell>
      <TableCell Background="LightGray"><Paragraph>Cell 3</Paragraph></TableCell>
    </TableRow>
  </TableRowGroup>
</Table>

A figura a seguir mostra como o exemplo é renderizado.

Captura de tela: Célula abrangendo todas as três colunas

Construindo uma Tabela com Código

Os exemplos a seguir mostram como criar programaticamente uma Table e populá-la com conteúdo. Os conteúdos da tabela são particionados em cinco linhas (representadas por objetos TableRow contidos em um objeto RowGroups) e seis colunas (representadas por objetos TableColumn). As linhas são utilizadas para diferentes propósitos de apresentação, incluindo uma linha de título pretendida para dar título a toda a tabela, uma linha de cabeçalho para descrever as colunas de dados na tabela, e uma linha de rodapé com informações de resumo. Observe que a noção de linhas de título, cabeçalho e rodapé não são inerentes à tabela; são simplesmente linhas com difernentes características. Células de tabela contêm o conteúdo real, que pode compreender texto, imagens ou quase qualquer outro elemento interface do usuário (UI).

ObservaçãoObservação:

Para obter um exemplo completo que demonstra o código de exemplo abaixo, consulte Exibindo dados tabulares em um exemplo de tabela.

Primeiro, um FlowDocument é criado para hospedar o Table, e um novo Table é criado e acrescentado aos conteúdos do FlowDocument.

' Create the parent FlowDocument...
flowDoc = New FlowDocument()

' Create the Table...
table1 = New Table()

' ...and add it to the FlowDocument Blocks collection.
flowDoc.Blocks.Add(table1)


' Set some global formatting properties for the table.
table1.CellSpacing = 10
table1.Background = Brushes.White
// Create the parent FlowDocument...
flowDoc = new FlowDocument();

// Create the Table...
table1 = new Table();
// ...and add it to the FlowDocument Blocks collection.
flowDoc.Blocks.Add(table1);


// Set some global formatting properties for the table.
table1.CellSpacing = 10;
table1.Background = Brushes.White;

Em seguida, seis objetos TableColumn são criados e acrescentados à coleção Columns da tabela, com alguma formatação aplicada.

ObservaçãoObservação:

Observe que, da tabela Columns coleção usa o padrão de indexação com base em zero.

' Create 6 columns and add them to the table's Columns collection.
Dim numberOfColumns = 6
Dim x
For x = 0 To numberOfColumns
    table1.Columns.Add(new TableColumn())

    ' Set alternating background colors for the middle colums.
    If x Mod 2 = 0 Then
      table1.Columns(x).Background = Brushes.Beige
    Else
      table1.Columns(x).Background = Brushes.LightSteelBlue
    End If
Next x

// Create 6 columns and add them to the table's Columns collection.
int numberOfColumns = 6;
for (int x = 0; x < numberOfColumns; x++)
{
    table1.Columns.Add(new TableColumn());

    // Set alternating background colors for the middle colums.
    if(x%2 == 0)
        table1.Columns[x].Background = Brushes.Beige;
    else
        table1.Columns[x].Background = Brushes.LightSteelBlue;
}

Em seguida, uma linha de título é criada e acrescentada para a tabela com alguma formatação aplicada. A linha de título contém uma única célula que ocupa todas as seis colunas na tabela.

' Create and add an empty TableRowGroup to hold the table's Rows.
table1.RowGroups.Add(new TableRowGroup())

' Add the first (title) row.
table1.RowGroups(0).Rows.Add(new TableRow())

' Alias the current working row for easy reference.
Dim currentRow As New TableRow()
currentRow = table1.RowGroups(0).Rows(0)

' Global formatting for the title row.
currentRow.Background = Brushes.Silver
currentRow.FontSize = 40
currentRow.FontWeight = System.Windows.FontWeights.Bold

' Add the header row with content, 
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("2004 Sales Project"))))
' and set the row to span all 6 columns.
currentRow.Cells(0).ColumnSpan = 6
// Create and add an empty TableRowGroup to hold the table's Rows.
table1.RowGroups.Add(new TableRowGroup());

// Add the first (title) row.
table1.RowGroups[0].Rows.Add(new TableRow());

// Alias the current working row for easy reference.
TableRow currentRow = table1.RowGroups[0].Rows[0];

// Global formatting for the title row.
currentRow.Background = Brushes.Silver;
currentRow.FontSize = 40;
currentRow.FontWeight = System.Windows.FontWeights.Bold;

// Add the header row with content, 
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("2004 Sales Project"))));
// and set the row to span all 6 columns.
currentRow.Cells[0].ColumnSpan = 6;

Em seguida, uma linha de cabeçalho é criada e acrescentada à tabela, e as células da linha de cabeçalho são criadas e populadas com conteúdo.

' Add the second (header) row.
table1.RowGroups(0).Rows.Add(new TableRow())
currentRow = table1.RowGroups(0).Rows(1)

' Global formatting for the header row.
currentRow.FontSize = 18
currentRow.FontWeight = FontWeights.Bold

' Add cells with content to the second row.
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Product"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 1"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 2"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 3"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 4"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("TOTAL"))))
// Add the second (header) row.
table1.RowGroups[0].Rows.Add(new TableRow());
currentRow = table1.RowGroups[0].Rows[1];

// Global formatting for the header row.
currentRow.FontSize = 18;
currentRow.FontWeight = FontWeights.Bold;

// Add cells with content to the second row.
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Product"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 1"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 2"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 3"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Quarter 4"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("TOTAL"))));

Em seguida, uma linha de dados é criada e acrescentada à tabela, e as células desta linha são criadas e populadas com conteúdo. Construir essa linha é semelhante à construção da linha de cabeçalho, com uma formatação ligeiramente diferente aplicada.

' Add the third row.
table1.RowGroups(0).Rows.Add(new TableRow())
currentRow = table1.RowGroups(0).Rows(2)

' Global formatting for the row.
currentRow.FontSize = 12
currentRow.FontWeight = FontWeights.Normal

' Add cells with content to the third row.
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Widgets"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$50,000"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$55,000"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$60,000"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$65,000"))))
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$230,000"))))

' Bold the first cell.
currentRow.Cells(0).FontWeight = FontWeights.Bold
// Add the third row.
table1.RowGroups[0].Rows.Add(new TableRow());
currentRow = table1.RowGroups[0].Rows[2];

// Global formatting for the row.
currentRow.FontSize = 12;
currentRow.FontWeight = FontWeights.Normal;

// Add cells with content to the third row.
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Widgets"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$50,000"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$55,000"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$60,000"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$65,000"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("$230,000"))));

// Bold the first cell.
currentRow.Cells[0].FontWeight = FontWeights.Bold;

Finalmente, uma linha de rodapé é criada, acrescentada e formatada. Assim como a linha de título, o rodapé contém uma única célula que ocupa todas as seis colunas na tabela.

table1.RowGroups(0).Rows.Add(new TableRow())
currentRow = table1.RowGroups(0).Rows(4)

' Global formatting for the footer row.
currentRow.Background = Brushes.LightGray
currentRow.FontSize = 18
currentRow.FontWeight = System.Windows.FontWeights.Normal

' Add the header row with content, 
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Projected 2004 Revenue: $810,000"))))
' and set the row to span all 6 columns.
currentRow.Cells(0).ColumnSpan = 6
table1.RowGroups[0].Rows.Add(new TableRow());
currentRow = table1.RowGroups[0].Rows[4];

// Global formatting for the footer row.
currentRow.Background = Brushes.LightGray;
currentRow.FontSize = 18;
currentRow.FontWeight = System.Windows.FontWeights.Normal;

// Add the header row with content, 
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("Projected 2004 Revenue: $810,000"))));
// and set the row to span all 6 columns.
currentRow.Cells[0].ColumnSpan = 6;

Consulte também

Tarefas

Como: Definir uma Table com XAML

Como: Use elementos de conteúdo com fluxo

Conceitos

Flow Document Overview

Documentos em Windows Presentation Foundation