views:

468

answers:

3

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?

A: 

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.

Paul Sasik
A: 

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.

Andre Haverdings
+1  A: 

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).

viky