Share via


Vue d'ensemble de Table

Mise à jour : novembre 2007

Table est un élément de niveau bloc qui prend en charge la présentation basée sur grille du contenu de document dynamique. La flexibilité de cet élément le rend très utile, mais également plus compliqué à comprendre et à utiliser correctement.

Cette rubrique contient les sections suivantes.

  • Concepts de base d'une table

  • Comment une table est-elle différente d'une grille ?

  • Structure de base d'une table

  • Relation contenant-contenu d'une table

  • Groupements de lignes

  • Priorité de rendu d'arrière-plan

  • Répartition des lignes ou colonnes

  • Génération d'une table avec du code

  • Rubriques connexes

Concepts de base d'une table

Comment une table est-elle différente d'une grille ?

Table et Grid partagent des fonctionnalités communes, mais chacun d'eux est plus adapté à des scénarios différents. Table est conçu pour être utilisé au sein d'un contenu de flux (consultez Vue d'ensemble des documents dynamiques pour plus d'informations sur le contenu de flux). Les grilles fonctionnent de manière optimale dans les formulaires (en général n'importe où en dehors d'un contenu de flux). Dans un FlowDocument, Table prend en charge les comportements de contenu tels que la pagination, la gestion du rendu des colonnes et la sélection de contenu, tandis que Grid ne le fait pas. Grid fonctionne en revanche de manière optimale en dehors d'un FlowDocument pour de nombreuses raisons, dont le fait que Grid ajoute des éléments basés sur un index de ligne et de colonne, alors que Table ne le fait pas. L'élément Grid permet la superposition de contenus enfants, où plusieurs éléments peuvent exister dans une même « cellule ». Table ne prend pas en charge la superposition. Les éléments enfants d'un élément Grid peuvent être positionnés de façon absolue par rapport à la zone des limites de leur « cellule ». Table ne prend pas en charge cette fonctionnalité. Enfin, une Grid requiert moins de ressources qu'une Table, envisagez donc d'utiliser une Grid pour améliorer les performances.

Structure de base d'une table

Table fournit une présentation basée sur grille qui se compose de colonnes (représentées par les éléments TableColumn) et de lignes (représentées par les éléments TableRow ). Les éléments TableColumn n'hébergent pas de contenu. Ils définissent simplement les colonnes et les caractéristiques des colonnes. Les éléments TableRow doivent être hébergés dans un élément TableRowGroup, qui définit un regroupement de lignes pour la table. Les éléments TableCell, qui contiennent le contenu réel à présenter par la table doivent être hébergés dans un élément TableRow. TableCell peut contenir uniquement des éléments qui dérivent de Block. Les éléments enfants valides pour un TableCell incluent :

Remarque :

Les éléments TableCell ne peuvent pas héberger directement du contenu de texte. Pour plus d'informations sur les règles de relation contenant-contenu pour les éléments de contenu de flux comme TableCell, consultez Vue d'ensemble des documents dynamiques.

Remarque :

Table est identique à l'élément Grid mais présente davantage de fonctions et, par conséquent, requiert une charge de ressources plus importante.

L'exemple suivant définit une simple table de 2 x 3 avec 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>

L'illustration suivante montre comment s'affiche cet exemple.

Capture d'écran : affichage d'une table de base

Relation contenant-contenu d'une table

Table dérive de l'élément Block et adhère aux règles communes pour les éléments de niveau Block. Un élément Table peut être contenu par chacun des éléments suivants :

Groupements de lignes

L'élément TableRowGroup fournit un moyen de grouper arbitrairement des lignes dans une table; chaque ligne devant appartenir à un groupement de lignes. Les lignes dans un groupe de lignes partagent souvent un but commun et peuvent avoir le format d'un groupe. Une utilisation fréquente des groupements de lignes est de séparer des lignes à usage déterminé, telles qu'un titre, un en-tête et des lignes de pied de page, du contenu principal du tableau.

L'exemple suivant utilise XAML pour définir une table avec l'en-tête mis en forme avec des styles et lignes de pied de page.






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

L'illustration suivante montre comment s'affiche cet exemple.

Capture d'écran : groupes de lignes de la table

Priorité de rendu d'arrière-plan

Les éléments de table sont restitués dans l'ordre suivant (ordre de plan du plus bas au plus élevé). Cet ordre ne peut pas être modifié. Par exemple, il n'y a aucune propriété "ordre de plan" pour ces éléments que vous puissiez utiliser pour remplacer l'ordre établi.

  1. Table

  2. TableColumn

  3. TableRowGroup

  4. TableRow

  5. TableCell

Considérez l'exemple suivant, qui définit des couleurs d'arrière-plan pour chacun de ces éléments dans une table.

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

L'illustration suivante montre comment s'affiche cet exemple (affichage de couleurs d'arrière-plan uniquement).

Capture d'écran : ordre de plan de la table

Répartition des lignes ou colonnes

Les cellules de tableau peuvent être configurées pour couvrir plusieurs lignes ou colonnes en utilisant respectivement les attributs RowSpan ou ColumnSpan.

Considérez l'exemple suivant, dans lequel une cellule couvre trois colonnes.


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

L'illustration suivante montre comment s'affiche cet exemple.

Capture d'écran : cellule s'étendant sur les trois colonnes

Génération d'une table avec du code

Les exemples suivants indiquent comment créer un Table par programme et le remplir avec le contenu. Le contenu de la table est réparti en cinq lignes (représentées par les objets TableRow contenus dans un objet RowGroups) et six colonnes (représentées par les objets TableColumn). Les lignes sont utilisées à différentes fins de présentation, y compris une ligne de titre prévue pour intituler la table entière, une ligne d'en-tête pour décrire les colonnes de données dans la table et une ligne de pied de page avec les informations de résumé. Notez que les notions de lignes de « titre », d'« en-tête » et de « pied de page » ne sont pas inhérentes à la table ; ce sont simplement des lignes présentant des caractéristiques différentes. Les cellules de tableau contiennent le contenu réel, qui peut être composé de texte, d'images ou de presque tout autre élément interface utilisateur (UI).

Remarque :

Pour un exemple complet qui présente l'exemple de code affiché ci-dessous, consultez Affichage de données tabulaires dans un tableau, exemple.

En premier lieu, un FlowDocument est créé pour héberger la Table, et une nouvelle Table est créée et ajoutée au contenu du 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;

Ensuite, six objets TableColumn sont créés et ajoutés à la collection Columns de la table, avec l'application de quelques mises en forme.

Remarque :

Notez que la collection Columns de la table utilise une indexation standard commençant par zéro.

' 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;
}

Ensuite, une ligne de titre est créée et ajoutée à la table avec l'application de quelques mises en forme. La ligne de titre contient une cellule unique qui couvre les six colonnes de la table.

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

Ensuite, une ligne d'en-tête est créée et ajoutée à la table, et les cellules dans la ligne d'en-tête sont créées et sont remplies avec le contenu.

' 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"))));

Ensuite, une ligne pour les données est créée et ajoutée à la table, et les cellules dans cette ligne sont créées et remplies avec le contenu. La génération de cette ligne est semblable à la génération de la ligne d'en-tête, avec l'application d'une mise en forme légèrement différente.

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

Enfin, une ligne de pied de page est créée, ajoutée et mise en forme. Comme la ligne de titre, le pied de page contient une cellule unique qui couvre les six colonnes de la table.

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;

Voir aussi

Tâches

Comment : définir une table avec XAML

Comment : utiliser les éléments de contenu de flux

Concepts

Vue d'ensemble des documents dynamiques

Documents dans Windows Presentation Foundation