Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll the datagrid in stackpanel?

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!

like image 797
BarryLib Avatar asked Jul 17 '17 02:07

BarryLib


2 Answers

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>
like image 54
mm8 Avatar answered Sep 20 '22 17:09

mm8


DockPanel instead of StackPanel works for me.

like image 23
rosta Avatar answered Sep 22 '22 17:09

rosta