Search code examples
wpfxamlcomboboxselectedindex

ComboBoxItem to full width of ComboBox, when using SelectedIndex, or navigating keyboard?


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.


Solution

  • 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>