Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting TextTrimming (CharacterEllipsis) in DataGrid's Cell

I would like to apply TextTrimming property (CharacterEllipsis) to the text in WPF DataGrid cells.

DataGrid cells without TextTrimming set

I applied custom DataGridCell template as in this answer (code below) and it works well, except for the Hyperlink columns like the first one in the picture), which now are empty.

TextTrimming set on text columns, but hyperling column contents missing

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

I can see the difference in both column types in visual tree: Datagrid row in visual tree (when no custom template is applied)

but don't understand how I can use this information to apply TextTrimming to TextBlock's columns of both type. Thanks for your time ;)

like image 972
Paweł Bulwan Avatar asked Aug 07 '12 16:08

Paweł Bulwan


1 Answers

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.

like image 119
Paweł Bulwan Avatar answered Nov 15 '22 08:11

Paweł Bulwan