Make ComboBox stretch to available space with maxwidth and right-aligned parent

13.2k views Asked by At

I'm having a problem achieving the layout i want. This is my code:

<DockPanel DockPanel.Dock="Bottom" HorizontalAlignment="Right" LastChildFill="True">
                <Label DockPanel.Dock="Left" Content="Add new:"/>
                <Button DockPanel.Dock="Right" Content="Add" VerticalAlignment="Center"/>
                <ComboBox VerticalAlignment="Center" MaxWidth="150" HorizontalAlignment="Stretch">
                    <System:String>Item1</System:String>
                    <System:String>Item2</System:String>
                    <System:String>Item3</System:String>
                </ComboBox>
            </DockPanel>

What I want is to have the three elements aligned to the right, in the order Label, ComboBox, Button. The Label and the button should take as much space as needed, but I want the ComboBox to take as much space as possible up to 150 px. It kind of works when the DockPanel is not set to HorizontalAlignment=Right.

Any tips/solutions?

Thanks.

1

There are 1 answers

1
Nigel Shaw On

Use the RightToLeft setting, like this:

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
    <Grid FlowDirection="RightToLeft">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition MaxWidth="150"></ColumnDefinition>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
        </Grid.ColumnDefinitions>
            <Label FlowDirection="LeftToRight" Grid.Column="2" Content="Add new:"/>
            <ComboBox FlowDirection="LeftToRight" Grid.Column="1" VerticalAlignment="Center" MaxWidth="150" HorizontalAlignment="Stretch">
                <ComboBoxItem>Test</ComboBoxItem>
                <ComboBoxItem>Test</ComboBoxItem>
                <ComboBoxItem>Test</ComboBoxItem>
           </ComboBox>
         <Button FlowDirection="LeftToRight"  Grid.Column="0" DockPanel.Dock="Right" Content="Add" VerticalAlignment="Center"/>
     </Grid>
</Grid>

Here is is running:

Narrow

Wide