How to scroll the datagrid in stackpanel?

2019-07-27 07:06发布

I want to scroll the datagrid when it's length exceeds the stackpanel, so I tried this:

<StackPanel Orientation="Horizontal">                         
   <ScrollViewer VerticalScrollBarVisibility="Auto" CanContentScroll="True">
       <DataGrid Name="dgConfig" VerticalAlignment="Stretch" AutoGenerateColumns="False">
             <DataGrid.Columns>
              ...
             </DataGrid.Columns>
       </DataGrid>
   </ScrollViewer>                                
</StackPanel>

But this doesn't work, I have searched on this web and failed to find any avaiable solutions. So how should I fix this? Thanks!

3条回答
淡お忘
2楼-- · 2019-07-27 07:42

DockPanel instead of StackPanel works for me.

查看更多
男人必须洒脱
3楼-- · 2019-07-27 07:52

ScrollViewers and StackPanels don't work very well together since a StackPanel measures its child elements with infinite horizontal space if its Orientation property is set to Horizontal and infinite vertical space if it is set to Vertical.

So you will either have to specify a height for the StackPanel:

<StackPanel Orientation="Horizontal" Height="100">

If you don't it will have an infinite height and that's why you see no scrollbars.

The other, and much better option, would be to get rid of the StackPanel and use another Panel that doesn't measures its child elements with an infinite space.

The DataGrid has its own ScrollViewer built-in, so you don't need to put it inside a ScrollViewer element yourself. Get rid of the StackPanel(s) and the ScrollViewer:

<DataGrid Name="dgConfig" VerticalAlignment="Stretch" AutoGenerateColumns="False"
                          VerticalScrollBarVisibility="Auto">
    <DataGrid.Columns>
        ...
    </DataGrid.Columns>
</DataGrid>
查看更多
smile是对你的礼貌
4楼-- · 2019-07-27 07:58

try adding VerticalScrollBarVisibility="Auto", ScrollViewer.CanContentScroll="True" to datagrid property.

查看更多
登录 后发表回答