Adding ellipsis to your Silverlight TextBlocks
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.Text
;
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)