Search code examples
c#wpfxamlstackpaneldockpanel

How to make items in a DockPanel expand to fit all available space in WPF?


I have a StackPanel containing a StackPanel and some other items. The first StackPanel has a vertical orientation, the the inner one has a horizontal orientation. The inner one has a TreeView and a ListView, I would like them to expand and fit the width of the window, which I set by the window and allow the user to change. I would also like the outer StackPanel to fit the height of the window. How do I do this?

Edit: I've converted to using a DockPanel, and I've set the DockPanel.Dock properties correctly in each of the elements, and have disabled LastChildFill in both of the dockpanels, the layout still does not stretch.

The Code:

<Window x:Class="Clippy.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="400" Width="600" MinHeight="400" MinWidth="600" Loaded="Window_Loaded" SizeChanged="Window_SizeChanged">
    <DockPanel Name="wrapperDockPanel" LastChildFill="False">
        <Menu Height="22" Name="mainMenu" Width="Auto" DockPanel.Dock="Top" />
        <ToolBar Height="26" Name="mainToolBar" Width="Auto" DockPanel.Dock="Top" />
        <DockPanel Height="Auto" Name="contentDockPanel" DockPanel.Dock="Top" LastChildFill="False">
            <TreeView Name="categoryTreeView" />
            <ListView Name="clipListView" />
        </DockPanel>
        <StatusBar Height="23" Name="mainStatusBar" DockPanel.Dock="Top" />
    </DockPanel>
</Window>

Solution

  • This should do it - I set it up so that the TreeView and the ListView shared the main view 50/50; if you don't want that, set it to 'Auto' and '*' or something. Use "LastChildFill" to your advantage!

    <Window x:Class="Clippy.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="400" Width="600" MinHeight="400" MinWidth="600" Loaded="Window_Loaded" SizeChanged="Window_SizeChanged">
    
        <DockPanel LastChildFill="True">
            <Menu Width="Auto" DockPanel.Dock="Top" />
            <ToolBar Width="Auto" DockPanel.Dock="Top" />
            <StatusBar DockPanel.Dock="Bottom" />
    
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="0.5*" />
                    <RowDefinition Height="0.5*" />
                </Grid.RowDefinitions>
    
                <TreeView Name="categoryTreeView" Grid.Row="0" />
                <ListView Name="clipListView" Grid.Row="1" />
            </Grid>
        </DockPanel>
    
    </Window>