Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacement for missing TextTrimming option "CharacterEllipsis" in Silverlight

Silverlight (at least, as of Version 4) has no CharacterEllipsis option for TextTrimming, which WPF has. It could be used on a TextBlock. That means, If there is not enough room to display "That's incredible", I could trim to "That's..." but not to "That's incred..." which we'd rather want.

I though, we'd try to implement our custom text trimming function. Basically, thats not that hard. A quite stupid way is to measure the pixels for a string, compare to the available width and manipulate the string by cutting last character and adding "..." in a loop while the text still doesn't fit. Here is an example how this could work:

// Not perfect but good enough for us
private bool AutoTrim(string fullText, TextBlock textBlock, double maxWidth)
{
    double factor = maxWidth / textBlock.ActualWidth;
    if (factor > 1)
        return false;

    int newTextLength = (int)Math.Floor((double)fullText.Length * factor);
    string trimTest;
    do
    {
        trimTest = fullText.Substring(0, newTextLength--);
        textBlock.Text = trimTest + "..."; // problematic...
        factor = maxWidth / textBlock.ActualWidth;
    }
    while (factor < 1 && newTextLength > 0);

    return true;
}

But doing that in code behind (or within a Behavior) leads to some problems: For example, when we want to update the displayed text and set the TextBlock's TextBlock1.Text = ... Property, it actually might change our viewModel if the Text is bound to a ViewModel Property. Another problems occur as we noticed that view and viewModel might run of of sync for some reason (we noticed that in a ListBox).

Do you have a better idea on how to solve this problem in a good way?

like image 881
thmshd Avatar asked Nov 19 '25 08:11

thmshd


2 Answers

Robby Ingebretsen's DynamicTextBox does this by wrapping the TextBlock in a custom control and measuring the available size. It matches the CharacterEllipsis text trimming mode of WPF. WordEllipsis mode did get added to Windows Phone 7 Mango, but that isn't much help here.

like image 164
bkaid Avatar answered Nov 22 '25 04:11

bkaid


Dan Wahlin used a converter before TextTrimming="WordEllipsis" was added to Silverlight 4. You can find it here: http://weblogs.asp.net/dwahlin/archive/2010/05/05/text-trimming-in-silverlight-4.aspx

like image 34
Razvan Avatar answered Nov 22 '25 02:11

Razvan