WPF ScrollViewer around DataGrid affects column width

Jay picture Jay · Jul 26, 2013 · Viewed 12.2k times · Source

I have a problem with a ScrollViewer that I use to scroll a user control that contains a data grid. Without the scroll viewer the columns fill the data grid as I want but when adding a scroll viewer the columns shrink to ~15px. I was able to simplify my layout and can still reproduce this behaviour.

When binding the datagrid width to another control the columns have their normal with, but that has unsuprisingly the same effect as a fixed width on the datagrid. I guess I'm not the first one who has this problem. How can I work around this behaviour to have my grid adjusting its size to the available space and give it's columns a propotional width?

With scrollviewer: enter image description here and without: enter image description here

<Window x:Class="GridTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<Grid MinWidth="200">
    <DataGrid Margin="0" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Header="Column A" Width="*"/>
            <DataGridCheckBoxColumn Header="Column B" Width="*"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>
</ScrollViewer>

Answer

sa_ddam213 picture sa_ddam213 · Jul 26, 2013

Yeah, I had this problem a while ago, I resorted to a workaround, I will post here just incase its useful

<ScrollViewer HorizontalScrollBarVisibility="Auto">
    <Grid x:Name="grid" MinWidth="200">
        <DataGrid Width="{Binding ElementName=grid, Path=ActualWidth}">
            <DataGrid.Columns>
                <DataGridCheckBoxColumn Header="Column A" Width="1*"/>
                <DataGridCheckBoxColumn Header="Column B" Width="1*"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</ScrollViewer>

The trick was to give the DataGrid a width, in this case I bound back to the containing element

Or if you don't use the HorizontalScrollBar you can disable it, this will allow the ScrollViewer to calculate a width allowing the DataGrid to calculate a width.