How to scroll the datagrid in stackpanel?

99封情书 提交于 2019-12-11 08:45:51

问题


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!


回答1:


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>



回答2:


DockPanel instead of StackPanel works for me.




回答3:


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



来源:https://stackoverflow.com/questions/45135242/how-to-scroll-the-datagrid-in-stackpanel

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