WPF - Text box that grows vertically to accommodate all text

5.2k views Asked by At

The problem: I am not getting a textbox setting that will have a horizontally wordwrap and vertically auto grow functionality. I wish to do that by writing a code. I have written following code that creates a text box at mouse dblclick with wordwrap:

        TextBox text2 = new TextBox();
        text2.Width = 500;
        text2.Visibility = Visibility.Visible;
        text2.Focus();
        text2.Height = 30;
        text2.HorizontalAlignment = HorizontalAlignment.Left;
        text2.VerticalAlignment = VerticalAlignment.Top;
        Point p = e.GetPosition(LayoutRoot);
        text2.Margin = new Thickness(p.X, p.Y, 0, 0);
        LayoutRoot.Children.Add(text2);

But, textbox does not grow vertically. Can somebody suggest me a code in C# to do exactly what I desire?

3

There are 3 answers

0
Paul Sasik On

One way to accomplish the growth you're looking for is to use a string measuring mechanism which you would run any time the text in your text box changes. Simply measure and resize your text box accordingly with any change to the contents.

0
Andre Haverdings On

Have you tried this?

text2.Height = double.NaN; // or don't set the property, but some custom styles might give a default value ..
text2.TextWrapping = TextWrapping.Wrap;
text2.MinHeight = 30; // or not if you want the styles default

instead of

text2.Height = 30;

not setting it or using double.NaN is the same as using 'Auto' in xaml.

0
viky On

try using this

        Grid grid = new Grid();
        grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
        grid.RowDefinitions.Add(new RowDefinition());

        TextBox textBox = new TextBox() { Width = 100, TextWrapping = TextWrapping.Wrap };

        textBox.SetValue(Grid.RowProperty, 0);
        grid.Children.Add(textBox);
        window.Content = grid;

where window is the Name assigned to Window(root).