<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
拉伸(stretch)到 ComboboxItem
的大小?
最佳答案
事实证明,只有当发生 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>
代码隐藏
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show(comboBoxItem.ActualWidth.ToString());
}
当您启动应用程序时,ComboBoxItem 的 ActualWidth
为零,但是当 SelectionChanged
事件触发时,值将为 298。
解决方法
要解决此问题,请在开始处添加 ComboBoxItem
,例如:Select item
并为 ComboBox SelectedIndex="0"
设置,如下所示:
<ComboBox Width="300"
Height="30"
SelectedIndex="0">
<ComboBoxItem>Select item</ComboBoxItem>
...
关于c# - 如何在 ComboxItem 内将 DockPanel 的子宽度设置为 100%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22894523/