如何使 TextBox 填充所有可用的 space 而无需稍后调整其内容?

How to make TextBox fill all available space without later resizing to its content?

我有以下 Grid,里面有一个 TextBox

<UserControl ...>
 <Grid>
  <Grid.RowDefinitions>
   <RowDefinition Height="30px"/>
   <RowDefinition Height="Auto"/>
   <RowDefinition Height="Auto"/>
   <RowDefinition Height="1px"/>
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
   <ColumnDefinition Width="Auto"/>
   <ColumnDefinition Width="*"/>
  </Grid.ColumnDefinitions>
  <TextBox Grid.Column="1" Grid.RowSpan="3" AcceptsReturn="True"
   TextWrapping="Wrap" HorizontalScrollBarVisibility="Hidden"
   VerticalScrollBarVisibility="Visible" HorizontalAlignment="Stretch"
   VerticalAlignment="Stretch"/>
  <!-- content in other cells of the Grid's first column -->
 </Grid>
</UserControl>

我希望 TextBox 填充控件上可用的所有 space(宽度和高度方向),并且如果用户输入的文本多于适合它的文本,我想要它的垂直滚动条在不调整 TextBox 大小的情况下变为活动状态。相反,TextBox 的大小会发生变化以适应内容,并且整个网格会随之增长。

如何实现我的需求?

编辑: 下面是对所发生情况的说明。

上面的屏幕截图是内容适合 TextBox 的情况。下面的屏幕截图是当没有足够的空间来容纳所有内容时的情况 - TextBox 然后调整大小以适应它,这也会调整它所在的网格的大小,使其看起来破损。

编辑 2: 演示此行为的项目是 here

TextBox 没有填写 Grid。您可以通过为 Grid:

指定 Background 来自行确认
<UserControl>
    <Grid Background="Yellow">
    ...

这是因为 Grid 的高度是 30 px + 无论 TextBox 的高度是 + 1 px。为使第2行或第3行的内容填充Grid,需要将至少其中一个RowDefinitionsHeight改为*

<UserControl>
    <Grid Background="Yellow">
        <Grid.RowDefinitions>
            <RowDefinition Height="30px"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="1px"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBox Grid.Column="1" Grid.RowSpan="3" AcceptsReturn="True"
                 TextWrapping="Wrap" HorizontalScrollBarVisibility="Hidden"
                 VerticalScrollBarVisibility="Visible" HorizontalAlignment="Stretch"
                 VerticalAlignment="Stretch"/>
    </Grid>
</UserControl>

我设法通过在 GridTextBox 相同的单元格中添加一个不可见的 Border 来解决这个问题,然后设置 TextBox' WidthHeight 分别到 BorderActualWidthActualHeight

<Border x:Name="b" Grid.Column="1" Grid.RowSpan="3"
 HorizontalAlignment="Stretch"/>
<TextBox AcceptsReturn="True" TextWrapping="Wrap" Grid.Column="1"
 Grid.RowSpan="3" Width="{Binding ActualWidth, ElementName=b}"
 Height="{Binding ActualHeight, ElementName=b}"
 HorizontalScrollBarVisibility="Hidden"
 VerticalScrollBarVisibility="Visible" HorizontalAlignment="Stretch"
 VerticalAlignment="Stretch"/>

这导致 TextBox 保持固定 Height 而不管它的内容如何,​​但是它的 Width 还有另一个问题:当界面扩展时它会变大,但是之后没有缩水,因为底层ScrollViewer。诀窍是将 ScrollViewerHorizontalScrollBarVisibility 设置为 Disabled,而不是像我之前所做的那样 Hidden

我将示例项目的更改推送到 GitHub,因此解决方案现在可用 here