获取ComboBox项的宽度

时间:2010-10-26 15:14:58

标签: wpf layout combobox

我将combobox绑定到字符串[]。 我没有清楚的组合框项目。但我想衡量我的丢弃物品。 如何在运行时获取组合框中的项目宽度。我需要这个来管理我的组合的宽度。

2 个答案:

答案 0 :(得分:5)

如果你想这样做并且你不确定是否所有的ComboBoxItem都已生成,那么你可以使用这段代码。它会在代码后面扩展ComboBox,当它中的所有ComboBoxItem都被加载时,测量它们的大小,然后关闭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();
}

答案 1 :(得分:0)

尝试此功能:

foreach(var item in MyComboBox.Items){

    double width = item.ActualWidth;

}