Vignesh PT
Vignesh PT

Reputation: 644

Setting height of textbox to auto in code-behind for a dynamically created textbox

I am creating a textbox dynamically via code, and adding it to the LayoutRoot. I want the textbox to support multiline, so I have set the AcceptsReturn property to true and TextWrapping property to Wrap. I read in another question that to set the Height as Auto, we have to use double.NaN, and I have done this. But, when I add it, its height is infinite, and covers up the whole space. I just want the textbox to be of a single line initially and let it increase the height when lines are added to it. Please help me with this solution.

Upvotes: 1

Views: 5095

Answers (2)

naqvitalha
naqvitalha

Reputation: 793

A good alternative would be to create a resizable row in the grid and put the textBox in there.

<RowDefinition MinHeight="20"/>

Put your TextBox in this row:

Grid.SetRow(textBox,1);

Now if the height of textBox is Auto or, Double.NaN it should appropriately resize itself and the row.

Upvotes: 0

Kevin Aenmey
Kevin Aenmey

Reputation: 13429

Wrap your TextBox in a StackPanel. If you're doing it via code, you could do something like this, for example:

public MainPage()
{
    InitializeComponent();

    var textBox = new TextBox
    {
        AcceptsReturn = true,
        Height = Double.NaN,
        TextWrapping = TextWrapping.Wrap
    };

    var stackPanel = new StackPanel();
    stackPanel.Children.Add(textBox);

    this.LayoutRoot.Children.Add(stackPanel);
}

Upvotes: 4

Related Questions