当前位置: 首页 > 编程语言 > C#

从TabItem中获取并迭代控件?分享

时间:2023-04-11 00:56:04 C#

从TabItem获取并迭代控件?如何获取嵌套在Tabitem中的所有控件/UIElements(来自TabControl)?我尝试了一切,但无法得到它们。(设置SelectedTab):privateTabItemSelectedTab=null;privatevoidtabControl1_SelectionChanged(objectsender,SelectionChangedEventArgse){SelectedTab=(TabItem)tabControl1.SelectedItem;现在我需要这样的东西:privateStackPanelinconconlPanelInWhichLoadsfortabControl.Children/*doesntexist*/,ortabControl.Items/*onlyTabItems*/,or/*SelectedTab.Items??*/)//IHavenoplan{如果(控件是StackPanel){theStackPanelInWhichLabelsShouldBeLoaded=控件;//在Stackpanel中加载标签,这没有问题}}在Silvermind之后:执行此操作,Count始终为1:UpdateLayout();intnChildCount=VisualTreeHelper.GetChildrenCount(SelectedTab);TabControl具有Items属性(派生自ItemsControl),它返回所有TabItems-http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.items.aspx。或者您可以遍历可视化树:varfirstStackPanelInTabControl=FindVisualChildren(tabControl).First();使用:publicstaticIEnumerableFindVisualChildren(DependencyObjectrootObject)whereT:DependencyObject{if(rootObject!=null){for(inti=0;i(child))yieldreturnchildOfChild;}}}可能这个方法对你有帮助:foreach(DependencyObjectchildinchildren){//分析子对象是否匹配请求的类型if(child!=null&&childisT){yieldreturn(T)child;}//递归树foreach(TdescendantinFindChildren(child)){yieldreturndescendant;}}}}在此处查看完整文章(在WPF树中查找元素)。对我来说VisualTreeHelper.GetChildrenCount对于选项卡控件总是返回0,我只好改用这个方法如果分享的内容对你有用,需要了解更多C#学习教程,希望大家多多关注——publicstaticListObtenerControles(DependencyObjectparent)whereT:DependencyObject{Listresult=newList();if(parent!=null){foreach(varchildinLogicalTreeHelper.GetChildren(parent)){varchildType=childasT;如果(childType!=null){result.Add((T)child);}foreach(varotherinObtenerControles(childasDependencyObject)){result.Add(other);}}}返回结果;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: