Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give a WPF Grid the width of a ScrollViewer minus the scrollbar

I have a WPF UserControl with two Grids above each other. The bottom Grid is in a ScrollViewer. The idea is to have the first Grid be the header of the second Grid. I'm having trouble with the width of the columns however. Both Grids should take up all the space they can (the width of the Window), but the top Grid should of course be a little less wide, because there's a scrollbar on the right of the bottom Grid.

This is the simplified Xaml I've got:

<UserControl>
    <DockPanel>
        <Grid DockPanel.Dock="Top">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
        </Grid>
        <ScrollViewer>
            <Grid>
                <Grid.ColumnDefintions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefintions>
            </Grid>
        </ScrollViewer>
    </DockPanel>
</UserControl>

This renders fine actually, except that the most right column of the top Grid extends over the scrollbar, which I want to avoid.!

Here is an image of the result: Grid column and width of scrollbar. The red indicates where the column/cell is now, but I want it to stop at the blue line. I've tried SharedSizeGroups, but that seems to make my Grids small again (not take up the full space of the window).

like image 814
Peter Avatar asked Dec 28 '22 02:12

Peter


1 Answers

<ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" Name="sv">
    <Grid MinWidth="{Binding ElementName=sv, Path=ViewportWidth}" MinHeight="{Binding ElementName=sv, Path=ViewportHeight}" />
</ScrollViewer>

The problem is setting up a correct dependency between the ScrollViewer container size and the grid size. Let us consider just the width: the binding above allows the ScrollViewer to expose the horizontal scrollbar only if necessary:

enlarging a single column of the grid (eg. with a splitter) does not provoke the resizing of the other columns (which would happen if you bind Width instead MinWidth).

Using the ViewportWidth instead of ActualWidth takes into account the scrollbar width, if there is one.

Just try

like image 53
rpaulin56 Avatar answered May 06 '23 05:05

rpaulin56