Как обернуть длинный текст без пробелов или новой строки в DataGridViewTextBoxCell winforms (C #)? - PullRequest
0 голосов
/ 19 января 2012

Как обернуть длинный текст без пробелов или новой строки в DataGridViewTextBoxCell WinForms (C #)?

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if ((e.ColumnIndex == 1) && (e.FormattedValue != null))
    {
        SizeF sizeGraph = e.Graphics.MeasureString(e.FormattedValue.ToString(), e.CellStyle.Font, e.CellBounds.Width);

        RectangleF cellBounds = e.CellBounds;
        cellBounds.Height = cellBounds.Height;

        if (e.CellBounds.Height > sizeGraph.Height)
        {
            cellBounds.Y += (e.CellBounds.Height - sizeGraph.Height) / 2;
        }
        else
        {
            cellBounds.Y += paddingValue;
        }
        e.PaintBackground(e.ClipBounds, true);

        using (SolidBrush sb = new SolidBrush(e.CellStyle.ForeColor))
        {
            e.Graphics.DrawString(e.FormattedValue.ToString(), e.CellStyle.Font, sb, cellBounds);
        }
        e.Handled = true;
    }
}

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

1 Ответ

0 голосов
/ 22 января 2012

Не думаю, что есть способ использовать флаги форматирования для переноса одного слова в несколько строк.

Вы, вероятно, должны сделать это самостоятельно с помощью расчетов.

Пример (не оптимизирован по скорости):

private void PaintCell(Graphics g, Rectangle cellBounds, string longWord) {
  g.TextRenderingHint = TextRenderingHint.AntiAlias;
  float wordLength = 0;
  StringBuilder sb = new StringBuilder();
  List<string> words = new List<string>();

  foreach (char c in longWord) {
    float charWidth = g.MeasureString(c.ToString(), SystemFonts.DefaultFont,
                                      Point.Empty, StringFormat.GenericTypographic).Width;
    if (sb.Length > 0 && wordLength + charWidth > cellBounds.Width) {
      words.Add(sb.ToString());
      sb = new StringBuilder();
      wordLength = 0;
    }
    wordLength += charWidth;
    sb.Append(c);
  }

  if (sb.Length > 0)
    words.Add(sb.ToString());

  g.TextRenderingHint = TextRenderingHint.SystemDefault;
  g.DrawString(string.Join(Environment.NewLine, words.ToArray()),
               SystemFonts.DefaultFont,
               Brushes.Black,
               cellBounds,
               StringFormat.GenericTypographic);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...