<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
的大小?
答案 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>
...