19

I am trying to setup a list of items in WPF which contains strings of random length (people's names). The majority of them are generally within a certain size, but occasionally you come across a string so long that it runs out of the bounds of it's container. I've normally just truncated it when it's too long, but I would much rather show the entirety of the string.

How can I force the text to remain it's normal size, unless too big to fit...in which case scale it down to fit?

NOTE: This is not the same as scaling all text to fit a certain size, which is accomplished using a viewbox around the text

IE: This is NOT what I want:

<Viewbox MaxWidth="100">
    <TextBlock Text="{Binding EmployeeDisplayName, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Viewbox>

This makes everything scale up when too small, as well as scale down when too big. I ONLY want it to scale down when too big and NEVER scale up when too small...

Any thoughts?

Robert Petz
  • 2,718
  • 4
  • 23
  • 52
  • duplicate: https://stackoverflow.com/questions/14881683/wpf-automatic-resize-font-until-it-fits-within-parent-control – CAD bloke Feb 09 '18 at 21:26

1 Answers1

34

Use a Viewbox but set its StretchDirection property to DownOnly.

<Viewbox MaxWidth="100" StretchDirection="DownOnly">
    <TextBlock Text="{Binding EmployeeDisplayName, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" VerticalAlignment="Center"/>
</Viewbox>
keyboardP
  • 68,824
  • 13
  • 156
  • 205
  • 2
    Exactly what I was looking for. Man, I could NOT find this at all from Google, what a simple fix lol. I figured the WPF guys had thought about this at some point or another...Thanks – Robert Petz Aug 06 '13 at 02:46