Search code examples
c#wpfxamllayoutstackpanel

Can a Border fill the space of a Stackpanel without setting the width explicity?


Here is some xaml that displays a Stackpanel containing two Borders side by side. I want to make the second Border fill up the remaining area of the Stackpanel so that the red background of the Stackpanel can't be seen. But I see now way to do it other than setting an explicit width on the Border . Can it be done somehow without setting an explicit width?

<StackPanel Width="300" Background="Red" Orientation="Horizontal">
    <Border Width="100" Background="White">
        <TextBlock Text="Hello"/>
    </Border>
    <Border Background="Green">
        <TextBlock Text="World"/>
    </Border>
</StackPanel>

Solution

  • Not with a Stackpanel, no. The Stackpanel does not limit the width of its children. You should use either a Dockpanel or a Grid for this Layout.

    Something like

    <DockPanel Width="300" Background="Red">
        <Border Width="100" Background="White">
            <TextBlock Text="Hello"/>
        </Border>
        <Border Background="Green">
            <TextBlock Text="World"/>
        </Border>
    </DockPanel>