Search code examples
xamluwpwindows-8uwp-xamltextblock

Maximum number of lines for a Wrap TextBlock


I have a TextBlock with the following setting:

TextWrapping="Wrap"

Can I determine the maximum number of lines?

for example consider the following string TextBlock.Text:

This is a very good horse under the blackboard!!

It currently has been shows like this:

This is a very 
good horse under 
the blackboard!!

I need that to become something like:

This is a very 
good horse ...

any solution?


Solution

  • Update (for UWP)

    In UWP Apps you don't need this and can use the TextBlock property MaxLines (see MSDN)


    Original Answer:

    If you have a specific LineHeight you can calculate the maximum height for the TextBlock.

    Example:

    TextBlock with maximum 3 lines

    <TextBlock 
      Width="300"
      TextWrapping="Wrap" 
      TextTrimming="WordEllipsis" 
      FontSize="24" 
      LineStackingStrategy="BlockLineHeight"
      LineHeight="28"
      MaxHeight="84">YOUR TEXT</TextBlock>
    

    This is all that you need to get your requirement working.

    How to do this dynamically?

    Just create a new control in C#/VB.NET that extends TextBlock and give it a new DependencyProperty int MaxLines.
    Then override the OnApplyTemplate() method and set the MaxHeight based on the LineHeight * MaxLines.

    That's just a basic explanation on how you could solve this problem!