【问题标题】:textbox dynamically change height when the user goes to a new line当用户转到新行时,文本框会动态更改高度
【发布时间】:2012-08-04 18:02:35
【问题描述】:

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

谢谢

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

【问题讨论】:

    标签: c# wpf textbox height


    【解决方案1】:

    你说你需要使用文本框。您至少可以使用覆盖的文本框吗?这在我的测试中效果很好:

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

    【讨论】:

      【解决方案2】:

      我建议保持当前大小并使用垂直滚动条。但是,如果您正在做一些真正需要它的事情,请将您的 TextBox 放入一个网格中。将网格行高设置为自动。将文本框的高度设置为自动。将文本框的 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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-16
        • 2013-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-20
        相关资源
        最近更新 更多