Question

<ComboBoxItem HorizontalContentAlignment="Stretch" Width="Auto">
     <DockPanel Background="Red" HorizontalAlignment="Stretch" LastChildFill="True" Width="Auto">
        <Label DockPanel.Dock="Left" Name="lbName" ></Label>
        <Image DockPanel.Dock="Right" HorizontalAlignment="Right" Name="image" Source="/Test;component/Images/cross.jpg" Width="16" Height="16" Stretch="UniformToFill" />
        <Image DockPanel.Dock="Right" HorizontalAlignment="Right" Name="image2" Source="/Test;component/Images/cross.jpg" Width="16" Height="16" Stretch="UniformToFill" />
    </DockPanel>
</ComboBoxItem>

Like you can see on image below DockPanel(marked red) doesn't take 100% width of ComboboxItem.

How to stretch DockPanel to size of ComboboxItem in XAML?

enter image description here

Était-ce utile?

La solution

It turns out, that the content of the ComboBoxItem filled the entire space, only when an event SelectionChanged triggered.

Example:

XAML

<ComboBox Width="300"
          Height="30"
          SelectionChanged="ComboBox_SelectionChanged">

    <ComboBoxItem>Test</ComboBoxItem>

    <ComboBoxItem Name="comboBoxItem"
                  HorizontalContentAlignment="Stretch"                          
                  Width="Auto">

        <DockPanel Background="Red" 
                   HorizontalAlignment="Stretch" 
                   Width="Auto">                    
            ...
        </DockPanel>
    </ComboBoxItem>
</ComboBox>

Code-behind

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show(comboBoxItem.ActualWidth.ToString());
}

When you start the application ActualWidth of ComboBoxItem is zero, however when SelectionChanged event triggered value will be 298.

Workaround

For workaround add ComboBoxItem in begin, for example: Select item and set for ComboBox SelectedIndex="0" like this:

<ComboBox Width="300"
          Height="30"
          SelectedIndex="0">

    <ComboBoxItem>Select item</ComboBoxItem>
    ...

Autres conseils

Do not use the DockPanel for this kind of layout. Use a Grid instead:

<ComboBoxItem HorizontalContentAlignment="Stretch" Width="Auto">
    <Grid>
        <Grid.ColumnDefinitions>
           <ColumnDefinition Width="*" />
           <ColumnDefinition Width="Auto" />
           <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Label Grid.Column="0" Name="lbName" ></Label>
        <Image Grid.Column="1" Name="image" Source="/Test;component/Images/cross.jpg" Width="16" Height="16" Stretch="UniformToFill" />
        <Image Grid.Column="2" Name="image2" Source="/Test;component/Images/cross.jpg" Width="16" Height="16" Stretch="UniformToFill" />
    </Grid>
</ComboBoxItem>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top