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

WPF之TreeView查找节点

程序员文章站 2022-06-08 14:47:21
...
 private void tbDeviceType_TextChanged(object sender, TextChangedEventArgs e)
        {
            #region  源代码
            //if (tbDeviceType.Text == "")
            //{
            //    TreeViewTool.ItemsSource = listBoxItems;
            //}
            //else
            //{
            //    List<ListBoxItem> tempItems = new List<ListBoxItem>();
            //    foreach(var v in listBoxItems)
            //    {                  
            //        if(v.DisplayName.ToUpper().Contains(tbDeviceType.Text.ToUpper()) == true )
            //        {
            //            tempItems.Add(v);
            //        }
            //    }
            //    if(tempItems.Count == 0)
            //    {
            //        tempItems.Add(new ListBoxItem() { DisplayName = "Device Not Found." });
            //    }
            //    else
            //    {
            //    }
            //    TreeViewTool.ItemsSource = tempItems;

            //} 
            #endregion
            ListBoxItem item = null;
            string searchname = this.tbDeviceType.Text;
            foreach (var v in listBoxItems)
            {
                if (v.DisplayName.Contains(searchname))//模糊查询
                //if(v.DisplayName == searchname)
                {
                    item = v;
                    break;
                }
            }
            for (int i = 0; i < TreeViewTool.Items.Count; i++)
            {
                ListBoxItem v = TreeViewTool.Items.GetItemAt(i) as ListBoxItem;
                PareItems(TreeViewTool, v, item);
            }
             
        }

        //DFS搜索
        private void PareItems(ItemsControl itemsControl, ListBoxItem item, ListBoxItem TT)
        {
            TreeViewItem container = itemsControl.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

            if (container != null)
            {
                container.IsExpanded = true;

                if (container.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
                {
                    container.UpdateLayout();
                }
                if ((container.Header as ListBoxItem).Children != null)
                {
                    foreach (var it in (container.Header as ListBoxItem).Children)
                    {
                        PareItems(container, it, TT);
                    }
                }

                if ((container.Header as ListBoxItem) == TT)    //TT要找的子元素
                {

                    container.IsSelected = true;
                    container.BringIntoView();//滚动条滚动到选中的子元素
                }

                itemsControl = container;
            }
        }

 

相关标签: C#