当用户转到新行时,文本框会动态更改高度

时间:2012-08-07 17:05:52

标签: c# wpf textbox height

在WPF应用程序中,我有一个文本框。我已将AcceptReturn设为true 但是当用户点击Enter时,我需要使文本框更大。我的意思是当前用户点击回车键时,光标转到新行,但文本框仍然是相同的高度,现在隐藏了上面的行。我可以根据文本内容的内容动态更改textboxHeight吗?

谢谢

PS:我不能使用textarea我需要留在文本框

2 个答案:

答案 0 :(得分:1)

我建议保持当前大小并使用垂直滚动条。但是,如果您正在做一些真正需要它的东西,请将TextBox放入网格中。将网格行高度设置为自动。将TextBox的高度设置为Auto。将文本框的VerticalAlignment设置为Stretch。在下面的代码中,我保留了滚动条设置。您可以更改您认为合适的方式。

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

答案 1 :(得分:0)

你说你需要使用文本框。你至少可以使用覆盖文本框吗?这在我的测试中非常有效:

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

}