簡體   English   中英

如何在ComboxItem中將DockPanel的子級寬度設置為100%?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM