开发者

Get width of ComboBoxItem's

开发者 https://www.devze.com 2023-01-22 05:52 出处:网络
I\'ve got combobox binded to string[]. I haven\'t got clear combobox items. But I want measure my dropown items.

I've got combobox binded to string[]. I haven't got clear combobox items. But I want measure my dropown items. How can I get width of开发者_如何学JAVA items in combobox at runtime. I need this to manage width of my combo.


If you want to do this and you're not sure if all your ComboBoxItems have been generated then you can use this code. It will expand the ComboBox in code behind and when all the ComboBoxItems within it are loaded, measure their size, and then close the ComboBox.

The IExpandCollapseProvider is in 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();
}


Try this function:

foreach(var item in MyComboBox.Items){

    double width = item.ActualWidth;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消