c# - 如何在 ComboxItem 内将 DockPanel 的子宽度设置为 100%?

标签 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 拉伸(stretch)到 ComboboxItem 的大小?

enter image description here

最佳答案

事实证明,只有当发生 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/

相关文章:

c# - 是否可以编译使用 .NET DLL 和 GCC 的 C++?

c# - 如何在 C# 中创建动态 GroupBox

c# - 如何忽略 Entity Framework Core SQLite 数据库中的外键约束?

c# - 在文本框中发生任何更改时立即更改按钮的启用状态?

wpf - DataGridTextColumn 上的拼写检查器

wpf - 鼠标悬停时更改按钮的颜色

c# - .NET Core 中的 WebUtility.HtmlDecode 替换

WPF 与 Silverlight 3.0

c# - WPF:创建在构造函数中需要参数的应用程序资源 - 如何?

xaml - UWP 的日历日期选择器