如何在ComboxItem中将DockPanel的子宽度设置为100%?

时间:2014-04-06 13:14:39

标签: c# wpf xaml combobox dockpanel

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

如下图DockPanel(标记为红色)所示,ComboboxItem的宽度不是100%。

如何在XAML中将DockPanel拉伸到ComboboxItem的大小?

enter image description here

2 个答案:

答案 0 :(得分:2)

不要将DockPanel用于此类布局。改为使用Grid

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

答案 1 :(得分:2)

事实证明,只有当事件SelectionChanged被触发时,ComboBoxItem的内容才会填满整个空间。

示例:

<强> 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());
}

当您启动ComboBoxItem的应用程序ActualWidth为零时,但当SelectionChanged事件触发的值为298时。

<强> Workaround

要解决方法,请在开头添加ComboBoxItem,例如:Select item并设置为ComboBox SelectedIndex="0",如下所示:

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

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