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

Leave a Comment

(required) 
(required) 
(optional)
(required)