根据ComboBoxItem查找ComboBox

查找ComboBoxItem

ComboBoxItem cbi = (ComboBoxItem)(cb.ItemContainerGenerator.ContainerFromIndex(0));

根据ComboBoxItem查找ComboBox

var comboBox = ItemsControl.ItemsControlFromItemContainer(cbi) as ComboBox;

其实通过源码能直观的看到相应的转换过程,附源码如下

       ///
        /// Return the ItemsControl that owns the given container element
        ///
        public static ItemsControl ItemsControlFromItemContainer(DependencyObject container)
        {
            UIElement ui = container as UIElement;
            if (ui == null)
                return null;
 
            // ui appeared in items collection
            ItemsControl ic = LogicalTreeHelper.GetParent(ui) as ItemsControl;
            if (ic != null)
            {
                // this is the right ItemsControl as long as the item
                // is (or is eligible to be) its own container
                IGeneratorHost host = ic as IGeneratorHost;
                if (host.IsItemItsOwnContainer(ui))
                    return ic;
                else
                    return null;
            }
 
            ui = VisualTreeHelper.GetParent(ui) as UIElement;
 
            return ItemsControl.GetItemsOwner(ui);
        }
        
        
        /// 
        ///     Returns the ItemsControl for which element is an ItemsHost.
        ///     More precisely, if element is marked by setting IsItemsHost="true"
        ///     in the style for an ItemsControl, or if element is a panel created
        ///     by the ItemsPresenter for an ItemsControl, return that ItemsControl.
        ///     Otherwise, return null.
        /// 
        public static ItemsControl GetItemsOwner(DependencyObject element)
        {
            ItemsControl container = null;
            Panel panel = element as Panel;
 
            if (panel != null && panel.IsItemsHost)
            {
                // see if element was generated for an ItemsPresenter
                ItemsPresenter ip = ItemsPresenter.FromPanel(panel);
 
                if (ip != null)
                {
                    // if so use the element whose style begat the ItemsPresenter
                    container = ip.Owner;
                }
                else
                {
                    // otherwise use element's templated parent
                    container = panel.TemplatedParent as ItemsControl;
                }
            }
 
            return container;
        }

你可能感兴趣的:(根据ComboBoxItem查找ComboBox)