WPF TextBox and Scroll behavior

半腔热情 提交于 2019-11-26 19:02:29

The problem is that the parent elements are providing TextBox with as much space as it thinks it needs, and when more text is present it will expand instead of staying at the initial automatic size.

One solution here is to make another auto-sized element and bind the TextBox.Width to it:

<DockPanel>
    <TreeView Width="150" DockPanel.Dock="Left"/>
    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <TextBlock Margin="5" VerticalAlignment="Center" Text="Name"/>
            <Border x:Name="b" Grid.Column="1" Margin="5"/>
            <TextBox Width="{Binding ActualWidth, ElementName=b}"
                     MinWidth="200"
                     Grid.Column="1"
                     Margin="5"
                     VerticalAlignment="Center"
                     Text="Some Name"/>
        </Grid>
    </ScrollViewer>
</DockPanel>

Note that we set the Margin property of the auto-sizing element (the Border). This is important because if it's not set, there will be a loop:

  1. Border width autosizes to Grid column width
  2. TextBox width resizes to Border.ActualWidth
  3. Grid column width resizes to TextBox width + TextBox margin
  4. Border width autosizes to Grid column width again

By setting the Margin to the same as the TextBox, the resizing of the TextBox won't affect the Grid size.

chickenpie

Overriding TextBox.MeasureOverride like so worked for me:

protected override Size MeasureOverride(Size constraint)
{
    Size origSize = base.MeasureOverride(constraint);
    origSize.Width = MinWidth;
    return origSize;
}

no - this is a well known problem of wpf and is expected to be fixed in the next release. thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!