Search code examples
c#wpfstringxamltextblock

XAML TextBlock Binding with "..." at the end if text is too long


I have an ItemsControl with TextBlock inside. The TextBlock's text is Binded but if it is too long, it is truncated. I have already calculated the maximum character limit (20) and I would like that if it does not exceed them it is binded regularly, otherwise it is truncated but with "..." at the end. I think I know how to do in codebehind, but I would like to do it exclusively from XAML using (I think) the Style.


Solution

  • If you set TextTrimming="CharacterEllipsis" on your TextBlock that will give you the behavior you need automatically.

    If you need to enforce that 20 character limit, you can set a MaxWidth on your TextBlock to a value that gives you the width you need and TextTrimming will do the rest.