美文网首页
根据ComboBoxItem查找ComboBox

根据ComboBoxItem查找ComboBox

作者: ArtisCoder | 来源:发表于2019-09-25 23:30 被阅读0次

查找ComboBoxItem

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

根据ComboBoxItem查找ComboBox

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

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

       ///<summary>
        /// Return the ItemsControl that owns the given container element
        ///</summary>
        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);
        }
        
        
        /// <summary>
        ///     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.
        /// </summary>
        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

      本文链接:https://www.haomeiwen.com/subject/rwqaectx.html