如果单元格的内容大于其宽度,如何在DataGrid中显示省略号?

时间:2012-10-14 01:03:19

标签: c# wpf wpfdatagrid

如果DataGrid控件中某些单元格的内容大于为该列指定的宽度,是否可以显示...

类似的东西:

-------------------------------
|   Name   |    Last Name     |
-------------------------------
| LongNa.. |                  |
-------------------------------

2 个答案:

答案 0 :(得分:10)

TextTrimming正是您要找的。使用DataGridTemplateColumn并使单元格模板使用TextBlock,它提供TextTrimming的支持。样本 -

<DataGrid ItemsSource="{Binding ItemsSourceForYourGrid}">
   <DataGrid.Columns>
      <DataGridTemplateColumn Width="20">
         <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Name}" TextTrimming="CharacterEllipsis"/>
            </DataTemplate>
         </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

答案 1 :(得分:0)

是的,你可以。

试试这段代码,我认为这是有效的:

public static string StringEllipsis(DataGrid grid, string text, float columnWidth)
{
    // you can customize this variables, for your preferences
    string yourEllipsis = "..."; 
    string yourFontFamily = "Arial";
    float yourFontSize = 9F;
    float yourTolerance = 1F;

    Graphics graphics = grid.CreateGraphics();
    if (graphics.MeasureString(text, new Font(yourFontFamily, yourFontSize)).Width <= (columnWidth + yourTolerance))
        return text;

    while (graphics.MeasureString(text + yourEllipsis, new Font(yourFontFamily, yourFontSize)).Width > (columnWidth + yourTolerance))
        text = text.Substring(0, text.Length - 1);

    return text + yourEllipsis;
}

希望这有帮助!