C# – WPF How to make a Border width expand to fill available space in a DockPanel

c++wpfwpf-controls

I have a custom control ButtonRow which will end up going into a different control.

It is very simple, it has one Border, on label and one button.

I need to make it so that the border will extend its width to fill up to where the button is.
This is not happening as you can see in the below image:

Control Preview

The XAML can be found below. I have tried fiddling about with the horizontal alignment of both he label and the border, but they will only ever re-size to fit the text content of the label.

I know there are existing question with very similar problems and names, but none have needed to do quite the same thing or have helped me solve my problem.

I have tried using a StackPanel in horizontal alignment but all it did was make the button go next to the border.

How can I make the border expand to fill the available space?

<Grid>
    <DockPanel Height="Auto" HorizontalAlignment="Stretch" Margin="0" Name="dockPanel1" VerticalAlignment="Top" Width="Auto">
        <Border BorderBrush="#FFDADFE1" Background="#FFECF0F1" BorderThickness="1" Height="20" Name="bdrFilter" HorizontalAlignment="Stretch">
            <Label Content="Filter..." FontStyle="Italic" Foreground="#FF6C7A89" Height="20" Name="lblFilter" Padding="5,0" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" />
        </Border>
        <Button Style="{StaticResource FlatButtonStyle}" Content="+" Height="20" HorizontalAlignment="Right" Name="btnAddFilter" VerticalAlignment="Top" Width="20" Foreground="#FF6C7A89" ForceCursor="True" BorderBrush="{x:Null}" />
    </DockPanel>
</Grid>

(The button style does not affect its alignment or any other relevant properties)

Best Solution

A DockPanel is not the correct Panel to use for this requirement... like a StackPanel, it does not resize its contents. Instead, just use a regular Grid (which also uses less resources than a DockPanel):

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <Border BorderBrush="#FFDADFE1" Background="#FFECF0F1" BorderThickness="1" 
        Height="20" Name="bdrFilter" VerticalAlignment="Top">
        <Label Content="Filter..." FontStyle="Italic" Foreground="#FF6C7A89" 
            Height="20" Name="lblFilter" Padding="5,0" />
    </Border>
    <Button Grid.Column="1" Content="+" Height="20" HorizontalAlignment="Right" 
        Name="btnAddFilter" VerticalAlignment="Top" Width="20" Foreground="#FF6C7A89" 
        ForceCursor="True" BorderBrush="{x:Null}" />
</Grid>

Please see the Panels Overview page on MSDN for more information about the different Panels in WPF.

Related Question