Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Max Height for a dynamically sized WPF Textbox

Tags:

wpf

textbox

xaml

I'd like to make a TextBox in XAML that is dynamically sized to the content, but that has a max height that keeps it from growing forever if that text is very long. If that max height is reached, the TextBox should stop growing and instead show a scroll bar. Ideally, that scrollbar does not exist when the text fits. How would I go about that?

I gain the dynamic resizing property by simply not setting an explicit Height on the TextBox (and possibly turning on text wrapping). But achieving the max height and scroll bar is a mystery to me.

Currently I have a setup that always shows a scroll bar and that grows forever. How would I change this?

<ScrollViewer>
    <TextBox Text="{Binding Path=Selection.SummeryDescription, UpdateSourceTrigger=PropertyChanged}" />
</ScrollViewer>
like image 895
Drakestar Avatar asked Dec 05 '25 10:12

Drakestar


1 Answers

You can do that just by setting the ScrollViewer.VerticalScrollBarVisibility to Auto and the MaxHeight. See example below:

<TextBox Text="..." TextWrapping="Wrap" ScrollViewer.VerticalScrollBarVisibility="Auto" MaxHeight="500" />

This will only show a vertical scrollbar when needed.

Please notice that in my example the ScrollViewer element is omitted as I enable the ScrollViewer via the ScrollViewer.VerticalScrollBarVisibility property instead.

like image 128
Casper Taylor Korshøj Avatar answered Dec 07 '25 05:12

Casper Taylor Korshøj