简体   繁体   中英

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.

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM