Silverlight 4 Text Trimming

Silverlight 4 Another feature which was in WPF but not in Silverlight 3… TextTrimming is now available in Silverlight 4!

With previous version of Silverlight you could try some workaround (calculate the width of your text depending on the font size and family), but Silverlight 4 beta add a TextTrimming property to the TextBlock element to make it much easier!

A basic xaml sample looks like this:

<TextBlock Text="This is a text I want to trim"
TextTrimming="WordEllipsis" Width="140"></TextBlock>

And at runtime we get:
image

Same text, but let’s try to change the font and/or size:

<TextBlock Text="This is a text I want to trim"
FontFamily="Verdana" FontSize="18"
TextTrimming="WordEllipsis" Width="140"></TextBlock>

We get:
image

Note that VS2010 supports this in its design surface as well.

Silverlight 4 beta currently only supports WordEllipsis for TextTrimming (no CharacterEllipsis).

 

I wanted to try this in a different way so I added a DataGrid and filled it with a Sample Data Source in Expression Blend.

I have 3 columns:

    • Id: Width 35px
    • Name: Width 100px with TextTrimming
    • Description: Width * with TextTrimming
<data:DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Collection}" >
    <data:DataGrid.Columns>
        <!--Id Column-->
        <data:DataGridTextColumn Binding="{Binding Id}" Header="Id" Width="35"/>
        <!--Name Column-->
        <data:DataGridTemplateColumn Header="Name" Width="100">
            <data:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" TextTrimming="WordEllipsis"></TextBlock>
                </DataTemplate>
            </data:DataGridTemplateColumn.CellTemplate>
        </data:DataGridTemplateColumn>
        <!--Description Column-->
        <data:DataGridTemplateColumn Header="Description" Width="*">
            <data:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Description}" TextTrimming="WordEllipsis"></TextBlock>
                </DataTemplate>
            </data:DataGridTemplateColumn.CellTemplate>                        
        </data:DataGridTemplateColumn>                
    </data:DataGrid.Columns>
</data:DataGrid>

At runtime we get the second column text trimmed if longer than 100px, and the third column is trimmed depending on the browser size.

 

Note if the user resize the Name column, it automatically adds “…” if needed.

Also if user resize the whole browser window, the Description is trimmed as well.

 

 

Download source code

(requires Silverlight 4 beta)

 

 

Technorati Tags:

1 Comment

Comments have been disabled for this content.