Wpf 获取ComboBoxItem的宽度';s

Wpf 获取ComboBoxItem的宽度';s,wpf,layout,combobox,Wpf,Layout,Combobox,我已将组合框绑定到字符串[]。 我没有明确的组合框项目。但我想测量我自己的物品。 如何在运行时获取combobox中项目的宽度。我需要这个来管理组合的宽度。试试这个功能: foreach(var item in MyComboBox.Items){ double width = item.ActualWidth; } 如果要执行此操作,但不确定是否已生成所有ComboBoxItems,则可以使用此代码。它将在代码隐藏中展开ComboBox,当其中的所有ComboBoxItems都加

我已将组合框绑定到字符串[]。 我没有明确的组合框项目。但我想测量我自己的物品。 如何在运行时获取combobox中项目的宽度。我需要这个来管理组合的宽度。

试试这个功能:

foreach(var item in MyComboBox.Items){

    double width = item.ActualWidth;

}

如果要执行此操作,但不确定是否已生成所有ComboBoxItems,则可以使用此代码。它将在代码隐藏中展开ComboBox,当其中的所有ComboBoxItems都加载后,测量它们的大小,然后关闭ComboBox

IExpandCollapseProvider位于UIAutomationProvider中

public void SetComboBoxWidthFromItems()
{
    double comboBoxWidth = c_comboBox.DesiredSize.Width;

    // Create the peer and provider to expand the c_comboBox in code behind.
    ComboBoxAutomationPeer peer = new ComboBoxAutomationPeer(c_comboBox);
    IExpandCollapseProvider provider = (IExpandCollapseProvider)peer.GetPattern(PatternInterface.ExpandCollapse);
    EventHandler eventHandler = null;
    eventHandler = new EventHandler(delegate
    {
        if (c_comboBox.IsDropDownOpen &&
            c_comboBox.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
        {
            double width = 0;
            foreach (var item in c_comboBox.Items)
            {
                ComboBoxItem comboBoxItem = c_comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
                comboBoxItem.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
                if (comboBoxItem.DesiredSize.Width > width)
                {
                    width = comboBoxItem.DesiredSize.Width;
                }
            }
            c_comboBox.Width = comboBoxWidth + width;
            // Remove the event handler.
            c_comboBox.ItemContainerGenerator.StatusChanged -= eventHandler;
            c_comboBox.DropDownOpened -= eventHandler;
            provider.Collapse();
        }
    });
    // Anonymous delegate as event handler for ItemContainerGenerator.StatusChanged.
    c_comboBox.ItemContainerGenerator.StatusChanged += eventHandler;
    c_comboBox.DropDownOpened += eventHandler;
    // Expand the c_comboBox to generate all its ComboBoxItem's.
    provider.Expand();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    SetComboBoxWidthFromItems();
}

项是字符串,它没有实际宽度属性yperfect。你从哪里知道这个把戏的?我试了两天,也花了一段时间。我一点一点地把它弄明白了。ItemContainerGenerator.StatusChanged非常常见,但在本例中,它不足以满足约1%的情况,因此我还必须添加DropDownOpen事件。扩展和折叠的方法是通过google找到的:-)作为一个附加属性,或者仅仅是一个子类的实现,这将是非常棒的ComboBox@JJS:此处: