6

我想将 TextTrimming 属性 (CharacterEllipsis) 应用于 WPF DataGrid 单元格中的文本。

没有设置 TextTrimming 的 DataGrid 单元格

我在这个答案(下面的代码)中应用了自定义 DataGridCell 模板,它运行良好,除了图中第一个超链接列)现在是空的。

在文本列上设置了 TextTrimming,但缺少超文本列内容

<Style TargetType="DataGridCell">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Border Padding="3" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                    <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}">
                        <ContentPresenter.ContentTemplate>
                            <DataTemplate>
                                <TextBlock TextTrimming="CharacterEllipsis" Text="{Binding Text}"/>
                            </DataTemplate>
                        </ContentPresenter.ContentTemplate>
                    </ContentPresenter>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我可以在视觉树中看到两种列类型的区别: 可视化树中的数据网格行(未应用自定义模板时)

但不明白如何使用此信息将 TextTrimming 应用于 TextBlock 的两种类型的列。谢谢你的时间 ;)

4

1 回答 1

7

I finally ended up with the following solution (more like a workaround, but it works fine):

1) I assigned an x:Key to the style in question and applied it as a CellStyle to all DataGridTextColumns that should have their contents trimmed and ellipsisized whenever they don't fit

2) To apply ellipsis trimming in DataGridHyperlinkColumns, in App.xaml I added the following style:

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="TextTrimming" Value="CharacterEllipsis"></Setter>
</Style>

which will apply to all implicitly generated TextBlocks (as described in CodeNaked's answer). This might seem a bit overkill, but I can't see much difference in rendering performance and Hyperlinks are now trimmed as expected.

于 2012-08-16T13:54:52.290 回答