欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF后端选中treeview节点

程序员文章站 2022-06-08 13:54:37
...
/// <summary>
        /// 选择树的一个节点
        /// </summary>
        /// <param name="itemsControl">树控件名称</param>
        /// <param name="HeaderCl">根节点</param>
        /// <param name="ChildrenCl">想要选中的节点数据</param>
        /// <returns></returns>
        private bool SelectItems(ItemsControl itemsControl, PP_OrgInfo HeaderCl,PP_OrgInfo ChildrenCl)
        {
            TreeViewItem container = itemsControl.ItemContainerGenerator.ContainerFromItem(HeaderCl) as TreeViewItem;
            if (container != null)
            {
                container.IsExpanded = true;
                bool isExists = false;
                if (container.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
                {
                    container.UpdateLayout();
                }
                if ((container.Header as PP_OrgInfo).Children != null)
                {
                    for (int i = (container.Header as PP_OrgInfo).Children.Count - 1;i>=0 ; i--)
                    {
                        if (SelectItems(container, (container.Header as PP_OrgInfo).Children[i], ChildrenCl))
                        {
                            isExists = true;
                            break;
                        }
                    }
                }
                if (!isExists)
                {
                    if ((container.Header as PP_OrgInfo) == ChildrenCl)
                    {
                        container.IsSelected = true;
                        container.BringIntoView();//滚动条滚动到选中的子元素
                        return true;
                    }
                    else
                        return false;
                }
                else
                    return false;
            }
            else
            {
                return false;
            }
        }