문제

<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

도움이 되었습니까?

해결책

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

다른 팁

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>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top