4

Following XAML causes the "My stuff" being centered of ComboBox until I open the ComboBox, when it correctly stretches itself.

    <ComboBox Height="30" Width="300" HorizontalContentAlignment="Stretch" SelectedIndex="0">
        <ComboBoxItem HorizontalContentAlignment="Stretch">
            <Border Background="Red">
                <TextBlock>My stuff...</TextBlock>
            </Border>
        </ComboBoxItem>
    </ComboBox>

The question is, is it possible to get the ComboBoxItem being stretched even when it's selected using SelectedIndex? Same bug, or feature, happens if SelectedIndex is untouched (-1) and one selects the item using keyboard.

Workaround is probably to open the ComboBox programmatically in the beginning of app, which is rather ugly.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
Ciantic
  • 6,064
  • 4
  • 54
  • 49

2 Answers2

8

You just need to set the width of your border to the dynamic width of your outercontrol:

E.g.

Width="{Binding ElementName=combox1, Path=ActualWidth}">

Try this:

<ComboBox x:Name="combox1" Height="30" Width="300" HorizontalContentAlignment="Stretch" 
    SelectedIndex="0">
    <ComboBoxItem HorizontalContentAlignment="Stretch">
        <Border Background="Red" Width="{Binding ElementName=combox1, Path=ActualWidth}">
            <TextBlock>My stuff...</TextBlock>
        </Border>
    </ComboBoxItem>
</ComboBox>
Sheridan
  • 68,826
  • 24
  • 143
  • 183
codeB10
  • 116
  • 2
2

I see yes - i'm sure there is a way round this. It really depends what the end result is that you want. Do each of your data items have a difference background colour to identify them or is it simply a background colour to your whole combobox which you are trying to achieve.

If it is the latter, try this - and perhaps also remove the highlighted selection colour too, else perhaps the code behind route is correct, in terms of preselecting your first item, as that may be an option.

Example of All over Background colour:

    <ComboBox Background="Red" x:Name="combox2" Height="30" HorizontalContentAlignment="Stretch" SelectedIndex="0">
        <ComboBoxItem Background="Red" HorizontalContentAlignment="Stretch">
            <TextBlock Background="Red">My stuff...</TextBlock>
        </ComboBoxItem>
    </ComboBox>

Hope this helps! :)

Herman
  • 2,738
  • 19
  • 32
codeB10
  • 116
  • 2