You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让DataGrid列文本仅显示两行并添加省略号?

WPF DataGrid文本两行截断加省略号的实现方法

这个需求我之前做WPF项目时刚好碰到过,其实用TextBlock自带的属性就能轻松搞定,不用折腾复杂的自定义控件或者转换器~

核心就是给CellTemplate里的TextBlock设置三个关键属性:

  • TextWrapping="Wrap":让文本超出单元格宽度时自动换行
  • MaxLines="2":强制限制最多显示两行内容
  • TextTrimming="CharacterEllipsis":当内容超过两行时,在末尾自动添加省略号

给你一个完整的DataGrid列模板示例,直接套用就行:

<DataGridTemplateColumn Header="消息内容">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding YourMessageProperty}"
                       TextWrapping="Wrap"
                       MaxLines="2"
                       TextTrimming="CharacterEllipsis"
                       VerticalAlignment="Top"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

额外小提示:

如果发现省略号显示不正常,或者文本被单元格裁剪,可以检查这两点:

  1. 确保DataGrid单元格的高度足够容纳两行文本,你可以给列设置MinHeight,或者给TextBlock设置LineHeight来固定行高(比如LineHeight="22"),让两行的总高度更可控。
  2. 不要给TextBlock设置固定的Height,否则可能会覆盖MaxLines的效果,让文本无法正常换行和截断。

这个方案是WPF原生支持的,稳定性和兼容性都很好,我在多个项目里用过,完全能满足你的需求~

内容的提问来源于stack exchange,提问作者Bigeyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:58:39