Search code examples
wpfwpfdatagrid

Dock a resizable wpf DataGrid at bottom of window


In a WPF project, I want to dock a DataGrid to the bottom of a window so that if the window resizes, I will be able to utilize more of the DataGrid. Like this:

enter image description here

How do I do that? All my DockPanel attempts have failed.

The current attempt is here:

<Window x:Class="Foo.SQLDialog"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:c="clr-namespace:Foo.Controls"
   Title="test" ResizeMode="CanResize" Width="400" Height="400">
  <StackPanel Orientation="Vertical" Height="Auto" Width="Auto">
    <StackPanel Orientation="Vertical">
      <Label Content="SQL" HorizontalAlignment="Left"/>
      <TextBox Width="377" Height="100" Name="txtSQL"/>
      <Button Content="Run SQL" Click="Button_Click_1" />
    </StackPanel>
    <Label Content="Result" HorizontalAlignment="Left"/>
    <ScrollViewer Width="Auto" Height="180" DockPanel.Dock="Right,Bottom"
        ScrollViewer.CanContentScroll="True" 
        ScrollViewer.VerticalScrollBarVisibility="Auto"
        ScrollViewer.HorizontalScrollBarVisibility="Auto">
      <DataGrid x:Name="dataResult" />
    </ScrollViewer>
  </StackPanel>
</Window>

The height of the scrollviewer+datagrid will not adapt however.


Solution

  • First of all, using DockPanel.Dock without having a DockPanel as a parent doesn't do much...

    In my example I changed your root StackPanel to a DockPanel so it will work as you want.
    I also used DockPanel.LastChildFill property which makes sure the last child of the DockPanel will get all the remaining space:

    <DockPanel LastChildFill="True">
        <StackPanel Orientation="Vertical" DockPanel.Dock="Top">
            <Label Content="SQL" HorizontalAlignment="Left"/>
            <TextBox Width="377" Height="100" Name="txtSQL"/>
            <Button Content="Run SQL" Click="Button_Click_1" />
        </StackPanel>
        <Label Content="Result" HorizontalAlignment="Left" DockPanel.Dock="Top"/>
        <ScrollViewer DockPanel.Dock="Bottom,Right"
        ScrollViewer.CanContentScroll="True" 
        ScrollViewer.VerticalScrollBarVisibility="Auto"
        ScrollViewer.HorizontalScrollBarVisibility="Auto">
            <DataGrid x:Name="dataResult"  />
        </ScrollViewer>
    </DockPanel>
    

    Finally, to make it really stretch on all the remaining space, I removed the Height property you set, as this blocked it from stretching.