Adding ellipsis to your Silverlight TextBlocks

Published Wed, May 23 2007 23:37

Suppose you have a TextBlock and you need to make sure that its content isn't "cropped". In fact, what you'd like is to have "..." automatically appended to the portion of text that is shown to the user. Here's a method that does that:

private static string GetStringWithEllipsis(TextBlock txt)
{
  double actualWidth = txt.ActualWidth;
  double specWidth = txt.Width;
  if (specWidth> actualWidth)
  {
      return txt.Text;
  }
  TextBlock auxTxt = new TextBlock();
  auxTxt.FontFamily = txt.FontFamily;
  auxTxt.FontSize = txt.FontSize;
  auxTxt.FontWeight = txt.FontWeight;
  auxTxt.Text = "..."

  int i = 0;
  for (; i < txt.Text.Length; i++)
  {
      auxTxt.Text += txt.TextIdea;
      if (auxTxt.ActualWidth >= specWidth)
     {
         break;
      }
  }
  return i < txt.Text.Length ?
      string.Concat(txt.Text.Substring(0, i - 1), "...") : txt.Text;
}

I start by creating a dummy TextBlock that I'm using to copy the chars until its ActualWidth is bigger or equal to the specified width. So, if you have the following TextBlock:

<TextBlock x:Name="txt" Width="100" Height="100"
            Text="Just some info I've typed here" TextWrapping="NoWrap" />

You can simply call:

txt.Text = GetStringWithEllipsis(txt);

from your load event handler and you should be ready to go!

(thanks to Mark Rideout for the hints he gave me in the Silverlight forums)

Filed under:

Comments

# teksnqmbam said on Monday, August 27, 2007 10:13 PM

Hello! Good Site! Thanks you! gegisbiuwfcwwk

# shmoolca said on Tuesday, December 15, 2009 8:29 AM

You can use FormattedText instead of creating ui control.

# luisabreu said on Tuesday, December 15, 2009 4:19 PM

in 2009, sure...but I think that was not the case in May 2007...

# dadinn said on Friday, April 23, 2010 7:54 AM

check out this algorithm instead:

stackoverflow.com/.../2290045

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover