获取ComboBoxItem的宽度

And*_*kov 2 wpf layout combobox

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

Fre*_*lad 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();
}
Run Code Online (Sandbox Code Playgroud)