WPF之TreeView查找節點

 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;
            }
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章