Search code examples
wpfxamldatagridstackpanel

StackPanel interferes with sizing by margin


I have an app with a TabControl. On each TabItem is a DataGrid. The width and height are not set, the sizing is controlled by the margin so it sizes along with the tab.

<TabItem Name="tbRails" Header="Rails">
    <DataGrid x:Name="dgRails" Margin="5,30,5,5" ItemSource=...

This is all working fine until I needed to put a CheckBox on one of the tabs. We can only have one child on a TabItem so I added a StackPanel and put in the CheckBox and the DataGrid.

<TabItem Name="tbRails" Header="Rails">
    <StackPanel Name="pnlRails" Margin="10">
        <CheckBox Name="chkCollapseItems" Content="Collapse Items" Margin="15" Checked="chkCollapseItems_Checked" ... />
        <DataGrid  x:Name="dgRails" Margin="5,30,5,5" ItemSource=...

After doing this the data grid has no scrollbar and doesn't respond to mouse wheel. I can click on the cell and it gets selected and I can arrow key down until it disappears out of the bottom. The width sizes to the window just like it did before but it appears to be sizing its height to fit the content (about 2600 rows).

Has anyone seen this before and how do we fix it? I can set the height of the grid and it works just fine but it no longer sizes itself to match the parent.


Solution

  • Use a Grid as panel instead of a StackPanel. A stack panel will measure its children with positive infinity, which does not restrict their height. In other words, the DataGrid will be scaled to display all its records and therefore there will be no scroll viewer.

    Using a Grid with the RowDefinitions below, the CheckBox will size to fit its content and the DataGrid will get the rest of the available space in the TabItem.When this available space is not enough to display all records, it will automatically display a scrollbar.

    <TabItem Name="tbRails" Header="Rails">
       <Grid>
          <Grid.RowDefinitions>
             <RowDefinition Height="Auto"/>
             <RowDefinition/>
          </Grid.RowDefinitions>
          <CheckBox Grid.Row="0" Name="chkCollapseItems" Content="Collapse Items" Margin="15" Checked="chkCollapseItems_Checked" ... />
          <DataGrid Grid.Row="1"  x:Name="dgRails" Margin="5,30,5,5" ItemSource= ... />
       </Grid>
    </TabItem>