如何使TextBox填充所有可用空间而不稍后调整其内容?

问题描述 投票:1回答:2

我有以下GridTextBox

<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填充控件上可用的所有空间(宽度和高度),并且用户应该输入更多文本而不是适合它我希望它的垂直滚动条变为活动状态,而不调整TextBox的大小。相反的是,TextBox的大小会变化以适应内容,整个网格随之增长。

我如何实现我的需求?

编辑:以下是发生的事情的说明。 Two screenshots of the same <code>UserControl</code> with different content in <code>TextBox</code>.

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

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

wpf textbox user-controls grid
2个回答
0
投票

TextBox没有填补Grid。您可以通过为Background指定Grid来自行确认:

<UserControl>
    <Grid Background="Yellow">
    ...

这是因为Grid的高度是30 px +,无论TextBox的高度是+ 1 px。对于第2行或第3行的内容来填充Grid,您需要将Height中的至少一个的RowDefinitions更改为*

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

0
投票

我设法通过在BorderGrid的相同单元格中添加一个不可见的TextBox,然后将TextBox'WidthHeight分别设置为ActualWidthActualHeightBorder来解决这个问题:

<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设置为here

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

© www.soinside.com 2019 - 2024. All rights reserved.