WPF: How can I stretch the middle child in a DockPanel?

brgn picture brgn · Dec 26, 2012 · Viewed 18.6k times · Source

I added a DockPanel to a RadioButton element such that I can distribute the radio button label, a textbox and a button horizontally using 100% of the width.

Using LastChildFill="True"within the DockPanel stretches the last element. This works out nicely if the textbox is the last child in the panel. But, as the button is the last element and has a fixed width, the textbox should be stretched. However, there's no such property like 2ndChildFill="True".

My code looks like this:

    <RadioButton HorizontalAlignment="Stretch"
                                        HorizontalContentAlignment="Stretch">
        <DockPanel >
            <TextBlock VerticalAlignment="Center">in location:</TextBlock>
            <TextBox Grid.Column="1" Margin="10,0,0,0">Path string</TextBox>
            <Button HorizontalAlignment="Right" 
                    Margin="10,0,0,0" Padding="3,0">...</Button>
        </DockPanel>
    </RadioButton>

And it gives me this:

wpf screenshot

Any ideas, hints to fix this? Many thanks in advance...

Answer

max picture max · Dec 26, 2012

You need to set DockPanel.Dock attached property for your elements and leave TextBox as the last element:

<RadioButton HorizontalAlignment="Stretch"
             HorizontalContentAlignment="Stretch">
    <DockPanel LastChildFill="True">
        <TextBlock DockPanel.Dock="Left"
                   VerticalAlignment="Center"
                   Text="in location:" />
        <Button DockPanel.Dock="Right"
                Margin="10,0,0,0"
                Padding="3,0"
                Content="..." />
        <TextBox Margin="10,0,0,0">
            Path string
        </TextBox>
    </DockPanel>
</RadioButton>