Y2theZ
Y2theZ

Reputation: 10412

textbox dynamically change height when the user goes to a new line

In a WPF application I have a textbox. I have set AcceptReturn to true But I need to make the textbox bigger when the user clicks enter. What I mean is currently when the user clicks on the enter key, the cursor goes to a new line however the text box is still the same height and the above line is now hidden. Can I make the textboxHeight change dynamically depending on it's content?

Thanks

PS: I cannot use textarea I need to stay with the textboxes

Upvotes: 0

Views: 1859

Answers (2)

user12861
user12861

Reputation: 2426

You say you need to use Textboxes. Can you at least use an overriden Textbox? This worked pretty well in my testing:

public class AutoHeightTextbox : TextBox {

    protected override Size ArrangeOverride(Size arrangeBounds) {
        Size unboundSize = new Size(this.Width, double.PositiveInfinity);
        Size textSize = base.MeasureOverride(unboundSize);
        this.Height = textSize.Height;
        return base.ArrangeOverride(arrangeBounds);
    }

}

Upvotes: 0

Josh
Josh

Reputation: 2975

I would suggest to keep it a current size and use the vertical scrollbar. But, if you're doing something that really requires it, place your TextBox into a Grid. Set the Grid row height to auto. Set the Height of the TextBox to Auto. Set the VerticalAlignment of the textbox to Stretch. In the code below I left the scrollbar settings in. You can change those how you see fit.

     <Grid>
        <Grid.RowDefinitions>
           <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <TextBox Grid.Row="0" x:Name="scriptTextBox" Margin="10" Height="Auto" Width="Auto" FontFamily="Consolas, Courier New" 
                 HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"
                 MaxLines="9999" AcceptsReturn="True" AcceptsTab="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                 Text="{Binding Path=Script, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                 />
     </Grid>

Upvotes: 2

Related Questions