简体   繁体   中英

Why does a WPF ComboBox height expand to fill a grid cell, but not in a StackPanel?

This is the code that expands to fill the entire Grid cell:

<ComboBox Grid.Column="3" Grid.Row="1" >
  <ComboBoxItem>text1</ComboBoxItem>
  <ComboBoxItem>text2</ComboBoxItem>
  <ComboBoxItem>text3</ComboBoxItem>
  <ComboBoxItem>text4</ComboBoxItem>
</ComboBox>

But when I put this in a StackPanel inside the Grid cell it doesn't expand.

<StackPanel  Grid.Column="3" Grid.Row="1" Margin="10">
  <ComboBox>
    <ComboBoxItem>text1</ComboBoxItem>
    <ComboBoxItem>text2</ComboBoxItem>
    <ComboBoxItem>text3</ComboBoxItem>
    <ComboBoxItem>text4</ComboBoxItem>
  </ComboBox>
</StackPanel>

What causes the ComboBox to fill to the Height of the Grid cell in the first code above?

As a follow up, do we generally have to set a specific width for a ComboBox, or is there a better way other than locking the width or height down?

Grid and StackPanel behave differently.

By default, the HorizontalAlignment and VerticalAlignment of the control will be "Stretch". Grid's behaviour is to, indeed, stretch the control to the entire cell. However, a StackPanel is designed to just put controls underneath one another (if Orientation is Vertical). So, it ignores the "Stretch" VerticalAlignment in this case. It does follow it for the HorizontalAlignment, though.

So I'm afraid the answer is simply "that's how a StackPanel works". If you need stretching, you'll need a different control, like a Grid or UniformGrid.

For the width, that depends on your design. Usually you would use some combination of Margin, MinWidth and MaxWidth (or Height) to get the look you want.

What causes the ComboBox to fill to the Height of the Grid cell in the first code above?

Different panels have different characteristics.

A Grid stretches its child element to fill the available space whereas a StackPanel does not. Please refer to the following question more information about this.

Why StackPanel does not stretch its children vertically?

So in your example the Grid makes the StackPanel itself fill the available space but the StackPanel in turn doesn't make the ComboBox fill its available space.

You can confirm this by setting the Background property of the StackPanel to some brush. You will then see that the colour of this brush fills the entire cell of the Grid .

Unless I am mistaken, I appears that you have set a singular margin on your StackPanel, by default this sets all 4 margins simultaneously to that value. This will prevent it from filling the Grid cell

Because StackPanel 's MeasureOverride will limit the panel's rendered size to the minimum needed to render its child controls.

In your case it stops the ComboBox to fill the cell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM