DataGridViewRowPostPaintEventArgs Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Предоставляет данные для RowPostPaint события.
public ref class DataGridViewRowPostPaintEventArgs : EventArgs
public class DataGridViewRowPostPaintEventArgs : EventArgs
type DataGridViewRowPostPaintEventArgs = class
inherit EventArgs
Public Class DataGridViewRowPostPaintEventArgs
Inherits EventArgs
- Наследование
Примеры
В следующем примере кода показано, как обрабатывать RowPostPaint событие, чтобы содержимое ячейки охватывало всю строку. Этот пример кода является частью более крупного примера, предоставленного в разделе "Практическое руководство. Настройка внешнего вида строк в элементе управления DataGridView в Windows Forms".
// Paints the content that spans multiple columns and the focus rectangle.
void dataGridView1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
// Calculate the bounds of the row.
Rectangle rowBounds = new Rectangle(
this.dataGridView1.RowHeadersWidth, e.RowBounds.Top,
this.dataGridView1.Columns.GetColumnsWidth(
DataGridViewElementStates.Visible) -
this.dataGridView1.HorizontalScrollingOffset + 1,
e.RowBounds.Height);
SolidBrush forebrush = null;
try
{
// Determine the foreground color.
if ((e.State & DataGridViewElementStates.Selected) ==
DataGridViewElementStates.Selected)
{
forebrush = new SolidBrush(e.InheritedRowStyle.SelectionForeColor);
}
else
{
forebrush = new SolidBrush(e.InheritedRowStyle.ForeColor);
}
// Get the content that spans multiple columns.
object recipe =
this.dataGridView1.Rows.SharedRow(e.RowIndex).Cells[2].Value;
if (recipe != null)
{
String text = recipe.ToString();
// Calculate the bounds for the content that spans multiple
// columns, adjusting for the horizontal scrolling position
// and the current row height, and displaying only whole
// lines of text.
Rectangle textArea = rowBounds;
textArea.X -= this.dataGridView1.HorizontalScrollingOffset;
textArea.Width += this.dataGridView1.HorizontalScrollingOffset;
textArea.Y += rowBounds.Height - e.InheritedRowStyle.Padding.Bottom;
textArea.Height -= rowBounds.Height -
e.InheritedRowStyle.Padding.Bottom;
textArea.Height = (textArea.Height / e.InheritedRowStyle.Font.Height) *
e.InheritedRowStyle.Font.Height;
// Calculate the portion of the text area that needs painting.
RectangleF clip = textArea;
clip.Width -= this.dataGridView1.RowHeadersWidth + 1 - clip.X;
clip.X = this.dataGridView1.RowHeadersWidth + 1;
RectangleF oldClip = e.Graphics.ClipBounds;
e.Graphics.SetClip(clip);
// Draw the content that spans multiple columns.
e.Graphics.DrawString(
text, e.InheritedRowStyle.Font, forebrush, textArea);
e.Graphics.SetClip(oldClip);
}
}
finally
{
forebrush.Dispose();
}
if (this.dataGridView1.CurrentCellAddress.Y == e.RowIndex)
{
// Paint the focus rectangle.
e.DrawFocus(rowBounds, true);
}
}
' Paints the content that spans multiple columns and the focus rectangle.
Sub dataGridView1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles dataGridView1.RowPostPaint
' Calculate the bounds of the row.
Dim rowBounds As New Rectangle(Me.dataGridView1.RowHeadersWidth, _
e.RowBounds.Top, Me.dataGridView1.Columns.GetColumnsWidth( _
DataGridViewElementStates.Visible) - _
Me.dataGridView1.HorizontalScrollingOffset + 1, e.RowBounds.Height)
Dim forebrush As SolidBrush = Nothing
Try
' Determine the foreground color.
If (e.State And DataGridViewElementStates.Selected) = _
DataGridViewElementStates.Selected Then
forebrush = New SolidBrush(e.InheritedRowStyle.SelectionForeColor)
Else
forebrush = New SolidBrush(e.InheritedRowStyle.ForeColor)
End If
' Get the content that spans multiple columns.
Dim recipe As Object = _
Me.dataGridView1.Rows.SharedRow(e.RowIndex).Cells(2).Value
If (recipe IsNot Nothing) Then
Dim text As String = recipe.ToString()
' Calculate the bounds for the content that spans multiple
' columns, adjusting for the horizontal scrolling position
' and the current row height, and displaying only whole
' lines of text.
Dim textArea As Rectangle = rowBounds
textArea.X -= Me.dataGridView1.HorizontalScrollingOffset
textArea.Width += Me.dataGridView1.HorizontalScrollingOffset
textArea.Y += rowBounds.Height - e.InheritedRowStyle.Padding.Bottom
textArea.Height -= rowBounds.Height - e.InheritedRowStyle.Padding.Bottom
textArea.Height = (textArea.Height \ e.InheritedRowStyle.Font.Height) * _
e.InheritedRowStyle.Font.Height
' Calculate the portion of the text area that needs painting.
Dim clip As RectangleF = textArea
clip.Width -= Me.dataGridView1.RowHeadersWidth + 1 - clip.X
clip.X = Me.dataGridView1.RowHeadersWidth + 1
Dim oldClip As RectangleF = e.Graphics.ClipBounds
e.Graphics.SetClip(clip)
' Draw the content that spans multiple columns.
e.Graphics.DrawString(text, e.InheritedRowStyle.Font, forebrush, _
textArea)
e.Graphics.SetClip(oldClip)
End If
Finally
forebrush.Dispose()
End Try
If Me.dataGridView1.CurrentCellAddress.Y = e.RowIndex Then
' Paint the focus rectangle.
e.DrawFocus(rowBounds, True)
End If
End Sub
Комментарии
Событие RowPostPaint возникает после того, как строка нарисована на DataGridView элементе управления. RowPostPaint позволяет вручную настроить внешний вид строки после того, как ячейки в строке окрашены. Это полезно, если вы хотите настроить строку.
Конструкторы
| Имя | Описание |
|---|---|
| DataGridViewRowPostPaintEventArgs(DataGridView, Graphics, Rectangle, Rectangle, Int32, DataGridViewElementStates, String, DataGridViewCellStyle, Boolean, Boolean) |
Инициализирует новый экземпляр класса DataGridViewRowPostPaintEventArgs. |
Свойства
| Имя | Описание |
|---|---|
| ClipBounds |
Возвращает или задает область DataGridView , которая должна быть переопределена. |
| ErrorText |
Возвращает строку, представляющую сообщение об ошибке для текущего DataGridViewRow. |
| Graphics |
Возвращает используемый Graphics для рисования текущего DataGridViewRow. |
| InheritedRowStyle |
Возвращает стиль ячейки, примененный к текущему DataGridViewRow. |
| IsFirstDisplayedRow |
Возвращает значение, указывающее, является ли текущая строка первой строкой, отображаемой в .DataGridView |
| IsLastVisibleRow |
Возвращает значение, указывающее, является ли текущая строка последней видимой строкой, отображаемой в объекте DataGridView. |
| RowBounds |
Получение границ текущего DataGridViewRow. |
| RowIndex |
Возвращает индекс текущего DataGridViewRow. |
| State |
Возвращает состояние текущего DataGridViewRow. |
Методы
| Имя | Описание |
|---|---|
| DrawFocus(Rectangle, Boolean) |
Рисует прямоугольник фокуса вокруг указанных границ. |
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| PaintCells(Rectangle, DataGridViewPaintParts) |
Закрашивает указанные части ячейки для области в указанных границах. |
| PaintCellsBackground(Rectangle, Boolean) |
Закрашивает фон ячейки для области в указанных границах. |
| PaintCellsContent(Rectangle) |
Закрашивает содержимое ячейки для области в указанных границах. |
| PaintHeader(Boolean) |
Закрашивает весь заголовок строки текущего DataGridViewRow. |
| PaintHeader(DataGridViewPaintParts) |
Закрашивает указанные части заголовка строки текущей строки. |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |