Поделиться через


Общие сведения о таблицах

Обновлен: Ноябрь 2007

Table ― это элемент уровня блока, который поддерживает представление содержимого документа в виде сетки. Гибкость этого элемента делает его очень полезным, но также делает более сложным для понимания и для правильного использования.

В этом разделе содержатся следующие подразделы.

  • Основные сведения о таблицах

  • Отличие таблицы от сетки

  • Основная структура таблицы

  • Вложенность таблицы

  • Группировки строк

  • Приоритет отрисовки фона

  • Объединение строк или столбцов

  • Создание таблицы с помощью кода

  • См. также

Основные сведения о таблицах

Отличие таблицы от сетки

Элементы Table и Grid имеют некоторые общие функциональные возможности, но каждый из них наилучшим образом подходит для различных сценариев. Table предназначена для использования внутри содержимого потока (см. раздел Общие сведения о документе нефиксированного формата для получения дополнительных сведений о содержимом потока). Сетку лучше всего использовать внутри форм (главным образом, где-либо вне содержимого потока). Внутри FlowDocument элемент Table поддерживает такие возможности, как разбиение на страницы, обратный порядок столбцов и выделение содержимого, в то время как Grid их не поддерживает. С другой стороны элемент Grid лучше всего использовать вне FlowDocument по многим причинам, включая то, что Grid добавляет элементы на основе индексов строки и столбца, в то время как Table ― нет. Элемент Grid позволяет послойно размещать дочернее содержимое, что дает возможность разместить в одной «ячейке» несколько элементов. Table не поддерживает послойное размещение. Дочерние элементы Grid могут быть абсолютно расположенными относительно границ «ячейки».Table не поддерживает этой возможности. Наконец, для элемента Grid требуется меньше ресурсов, чем для Table, поэтому рассмотрите возможность использования Grid для повышения производительности.

Основная структура таблицы

Table обеспечивает сеточное представление, состоящее из столбцов (представленных элементами TableColumn) и строк (представленных элементами TableRow). Элементы TableColumn не содержат данных; они просто определяют столбцы и их характеристики. Элементы TableRow должны быть расположены в элементе TableRowGroup, определяющем группировку строк для таблицы. Элементы TableCell, содержащие фактические данные, отображаемые в таблице, должны быть расположены в элементе TableRow. TableCell может содержать только элементы, производные от Block. Допустимые дочерние элементы для TableCell.

ms747133.alert_note(ru-ru,VS.90).gifПримечание.

Элементы TableCell могут не содержать текстовых данных. Дополнительные сведения об ограничительных правилах для элементов потока содержимого, таких, как TableCell, см. в разделе Общие сведения о документе нефиксированного формата.

ms747133.alert_note(ru-ru,VS.90).gifПримечание.

Table подобна элементу Grid, но обладает дополнительными возможностями и, следовательно, требует больше ресурсов.

В следующем примере задается простая таблица 2 х 3 с помощью 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>

На следующем рисунке показан результат выполнения этого примера.

Снимок экрана: отображение простой таблицы

Вложенность таблицы

Table является производной от элемента Block и наследует общие правила для элементов уровня Block. Элемент Table может содержаться в одном из следующих элементов:

Группировки строк

Элемент TableRowGroup предоставляет способ произвольной группировки строк в таблице; каждая строка в таблице должна принадлежать группе строк. Строки в группе обычно имеют общее назначение, и для строк в группе может быть применен общий стиль. Чаще всего группировки строк используются для отделения строк специального назначения, например строк названия, заголовка и нижнего колонтитула, от основного содержимого, находящегося в таблице.

В следующем примере с помощью XAML задается таблица с типовыми строками заголовка и колонтитула.






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

На следующем рисунке показан результат выполнения этого примера.

Снимок экрана: группы строк таблицы

Приоритет отрисовки фона

Элементы таблицы отображаются в следующем порядке (в z-порядке от нижнего к верхнему). Этот порядок изменить нельзя. Например, для этих элементов не существует свойства «Z-порядок», которое можно было бы использовать для переопределения установленного порядка.

  1. Table

  2. TableColumn

  3. TableRowGroup

  4. TableRow

  5. TableCell

Рассмотрим следующий пример, в котором задается цвет фона для каждого из этих элементов в пределах таблицы.

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

На следующем рисунке показан результат выполнения этого примера (отображение только цветов фона).

Снимок экрана: z-порядок таблицы

Объединение строк или столбцов

Можно настроить ячейки таблицы для объединения нескольких строк или столбцов с помощью свойств RowSpan или ColumnSpan соответственно.

Рассмотрим следующий пример, в котором ячейка объединяет три столбца.


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

На следующем рисунке показан результат выполнения этого примера.

Снимок экрана: интервал ячеек в трех столбцах

Создание таблицы с помощью кода

В следующих примерах показано, как программно создать Table и заполнить ее содержимым. Содержимое таблицы распределено по пяти строкам (представленным объектами TableRow, содержащимися в объекте RowGroups) и шести столбцам (представленным объектами TableColumn). Строки используются для различных целей представления, включая строку названия, предназначенную для заголовка всей таблицы, строку заголовка для описания столбцов данных в таблице, и строку нижнего колонтитула для итоговой информации. Обратите внимание, что строки «название», «заголовок» и «примечания» не встроены в таблицу; это просто строки с разными характеристиками. Ячейки таблицы содержат фактическое содержимое, которое может состоять из текста, изображений или практически любого другого элемента пользовательский интерфейс.

ms747133.alert_note(ru-ru,VS.90).gifПримечание.

Полный пример, демонстрирующий код, см. в разделе Пример отображения табличных данных.

Во-первых, создается FlowDocument для размещения Table, и создается новая Table, в которую добавляется содержимое из 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;

Далее, с применением некоторого форматирования создаются шесть объектов TableColumn, которые добавляются в коллекцию таблицы Columns.

ms747133.alert_note(ru-ru,VS.90).gifПримечание.

Обратите внимание, что коллекция таблицы Columns использует стандартное индексирование, начиная с нуля.

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

Далее, с применением некоторого форматирования создается строка названия и добавляется к таблице. Строка названия будет содержаться в одной ячейке, объединяющей все шесть столбцов таблицы.

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

Далее, создается и добавляется в таблицу строка заголовка, и ячейки в этой строке создаются и заполняются содержимым.

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

Далее, создается и добавляется в таблицу строка для данных, и ячейки в этой строке создаются и заполняются содержимым. Построение этой строки аналогично построению строки заголовка, с немного другим форматированием.

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

Наконец, создается, добавляется и форматируется строка нижнего колонтитула. Как и строка названия, нижний колонтитул содержится в одной ячейке, объединяющей все шесть столбцов таблицы.

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;

См. также

Задачи

Практическое руководство. Определение таблицы с помощью XAML

Практическое руководство. Использование содержимого нефиксированного формата

Основные понятия

Общие сведения о документе нефиксированного формата

Документы в Windows Presentation Foundation