WPF ScrollViewer around DataGrid affects column width

爷,独闯天下 提交于 2019-11-27 14:24:19

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.

I experienced the same thing last week.

Typically, this problem occurs when you have the following elements :

  1. A DataGrid with undefined width placed inside a ScrollViewer with the HorizontalScrollBarVisibility property set to Auto
  2. At least one DataGridColumn has an unlimited/undefined width (e.g : Width="*")


Actually, the solution depends on your needs :

  • Either you want your DataGridColumns to take all the available space of your DataGrid when the Window is showing (even if there's no displayed data) : in this case, sa_ddam213's answer can help you to cope with.
  • Or you don't mind having some blank spaces between your last column and the DataGrid right border on Window's first show.

For the last option, you just need to set fixed widths for your DataGridColumns (or just don't define it if you don't want to, this is not very important as columns can be easily resized by the user through a double-click). In this context, your DataGrid can be defined without a width.


Here is an example :

<ScrollViewer HorizontalScrollBarVisibility="Auto">
    <Grid x:Name="grid" MinWidth="200">
        <DataGrid>
            <DataGrid.Columns>
                <DataGridCheckBoxColumn Header="Column A" Width="100"/>
                <DataGridCheckBoxColumn Header="Column B" />
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</ScrollViewer>


By this way, if a column content runs over the container after a column auto-resizing, a horizontal scroll bar will appear.

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