[英]How to set children Width for DockPanel to 100% inside ComboxItem?
<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
大小?
不要將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>
事實證明,僅當事件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>
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.