首页 > 解决方案 > How to prevent outer scrollviewer from overriding inner scrollviewer?

问题描述

I have the following section within my Grid:

<ScrollViewer   Grid.Column="4" Grid.Row="0" CanContentScroll="True"  HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
    <StackPanel Orientation="Vertical" Margin="10" HorizontalAlignment="Stretch">

        <!-- other controls such as sliders, Textboxes and so on -->

        <Border Height="200" BorderThickness="1" BorderBrush="DarkGray" Margin="5" HorizontalAlignment="Stretch">
            <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="auto" >
                <TextBlock Text="{Binding LogOutput}" Style="{StaticResource BodyTextBlockStyle}" TextWrapping="NoWrap"/>
            </ScrollViewer>
        </Border>
    </StackPanel>
</ScrollViewer>

If I add a very long text into the LogOuput (tested with "Ipsum Lorem"), for some reason the width of my border increases and the outer ScrollViewer is showing a horizontal scrollbar.

What I would like to have, is that the width of the border doesn't change (always stretching to the available space of this grid column) and the inner ScrollViewer should show the horizontal scrollbar. I know I could achieve this, by setting a fixed width to the border, however - as mentioned - I want the border to stretch to the available space.

How can I achieve this?

标签: c#wpfxamlscrollbar

解决方案


You could bind the Width of inner ScrallViewer to the width of column:

<Border Height="200" BorderThickness="1" BorderBrush="DarkGray" Margin="5" HorizontalAlignment="Stretch"
        Width="{Binding Path=ColumnDefinitions[putColIndexHere], Converter={StaticResource ColDefinitionToWidthConverter}, ConverterParameter=30, RelativeSource={RelativeSource AncestorType=Grid}}">
    <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="auto" Background="Cyan"
                    >
        <TextBlock Text="{Binding StrTest}" TextWrapping="NoWrap"/>
    </ScrollViewer>
</Border>

and Convert method can looks like:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{   
    if(value is System.Windows.Controls.ColumnDefinition colDef)
    {
        return colDef.ActualWidth + colDef.Offset - int.Parse(parameter as string) ;
    }
    return value;
}

推荐阅读