2
votes

I am working on a WPF application and using a scrollViewer to view the content that is offlimit the screen area. Working fine, no issues.

But if my window contains a Listbox or Grid or anything like that and that control has many records then instead of adding a scrollbar to itself, it just increase the height of the control and window itself because scrollviewer believes it needs to extend.

I don't want to hardcode the listbox's height, because that make it same in different resolutions, i want to make it increase its height but not always as scrollviewer make it do so.

Thanks

2

2 Answers

6
votes

You can't include a variable height/width object inside a ScrollViewer without setting the height/width of the viewer.

The scroll viewer effectively has infinite height so the grid expands to fill the "available" space - hence the effect you are seeing. As @JoeWhite says in his comments, the ScrollViewer is a container that can be as tall as it needs to be to hold all of its content. Anchoring wouldn't help - in effect, your ListBox already is anchored, it's just anchored to something that says "oh, I'll be whatever size you need me to be".

You'll need to either restrict the height, move the ListBox outside the ScrollViewer or use something other than a ScrollViewer.

Again quoting @Joe "These are the hazards of putting a scrolling area inside another scrolling area - it's poor usability and it's hard to define the behaviour."

1
votes

You can wrap ScrollViewer into Grid, and bind scrollviewer's Width and Height properties to grid's ActualWidth and ActualHeight. So the scrollviewer will have fixed size equal to the size of the grid which will change when window resize.

Example:

<Grid x:Name="LayoutRoot" Background="White">
    <Grid Background="#FFF1F1F1" Height="49" VerticalAlignment="Top">
        <Button Content="Обзор" Margin="0,13,175.25,0" VerticalAlignment="Top" FontSize="14.667" HorizontalAlignment="Right" Width="95.147">
        </Button>
        <Label Content="{Binding DocPath, Converter={StaticResource FileNameConverter}, FallbackValue=Выберите файл, TargetNullValue=Выберите файл}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="342.603" Margin="10,10,0,0" Height="33"/>
        <Button Content="Загрузить данные" HorizontalAlignment="Right" Margin="0,13,10,0" VerticalAlignment="Top" Width="151.147" FontSize="14.667">
        </Button>
    </Grid>
    <Grid x:Name="scrollBorder" Margin="10,54,10,10">
        <ScrollViewer x:Name="LogScroller" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" 
                        HorizontalAlignment="Left" VerticalAlignment="Top" 
                        Height="{Binding ActualHeight, ElementName=scrollBorder}" Width="{Binding ActualWidth, ElementName=scrollBorder}" >
            <ItemsControl ItemsSource="{Binding Log}" />
        </ScrollViewer>
    </Grid>
</Grid>