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

11,506

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

Share:
11,506
KopfSick
Author by

KopfSick

Updated on June 27, 2022

Comments

  • KopfSick
    KopfSick about 2 years

    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.

  • ProfK
    ProfK over 6 years
    Where is the expanded DropDown the OP is looking for?