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

C# 如果单元格的内容大于其宽度,如何在DataGrid中显示省略号?,c#,wpf,datagrid,C#,Wpf,Datagrid,如果数据网格中某些单元格的内容大于指定的列宽,是否可以显示…? 比如: ------------------------------- | Name | Last Name | ------------------------------- | LongNa.. | | ------------------------------- 是的,你可以 试试这个代码,我想它会有用的: public static string StringEll

如果
数据网格
中某些单元格的内容大于指定的
列宽
,是否可以显示
? 比如:

-------------------------------
|   Name   |    Last Name     |
-------------------------------
| LongNa.. |                  |
-------------------------------
是的,你可以

试试这个代码,我想它会有用的:

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;
}
公共静态字符串字符串省略(DataGrid网格、字符串文本、float columnWidth)
{
//您可以根据自己的偏好自定义此变量
字符串yourEllipsis=“…”;
字符串yourFontFamily=“Arial”;
浮动大小=9F;
浮动公差=1F;
Graphics Graphics=grid.CreateGraphics();
if(graphics.MeasureString(文本,新字体(yourFontFamily,yourFontSize)).Width(columnWidth+yourTolerance))
text=text.Substring(0,text.Length-1);
返回文本+省略号;
}

文本修剪
就是您要找的。使用
DataGridTemplateColumn
并将
TextBlock
插入支持
texttiming
CellTemplate
。样品-

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

这对您有用吗?我以前用过这种方法。