如何(从TabControl)获取嵌套在Tabitem中的所有Controls/UIElement?
我什么都试过了,但没能买到。
(设置所选选项卡):
private TabItem SelectedTab = null;
private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedTab = (TabItem)tabControl1.SelectedItem;
}
现在我需要这样的东西:
private StackPanel theStackPanelInWhichLabelsShouldBeLoaded = null;
foreach (Control control in tabControl.Children /*doesnt exist*/, or tabControl.Items /*only TabItems*/, or /*SelectedTab.Items ??*/ ) //I Have no plan
{
if(control is StackPanel)
{
theStackPanelInWhichLabelsShouldBeLoaded = control;
//Load Labels in the Stackpanel, thats works without problems
}
}
Silvermind之后:这样做,计数总是1:
UpdateLayout();
int nChildCount = VisualTreeHelper.GetChildrenCount(SelectedTab);
TabControl具有Items属性(派生自ItemsControl),该属性返回所有TabItems-http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.items.aspx.或者你可以遍历视觉树:
var firstStackPanelInTabControl = FindVisualChildren<StackPanel>(tabControl).First();
使用:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject rootObject) where T : DependencyObject
{
if (rootObject != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(rootObject); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(rootObject, i);
if (child != null && child is T)
yield return (T)child;
foreach (T childOfChild in FindVisualChildren<T>(child))
yield return childOfChild;
}
}
}
这类方法可能会对您有所帮助:
public static IEnumerable<T> FindChildren<T>(this DependencyObject source)
where T : DependencyObject
{
if (source != null)
{
var childs = GetChildObjects(source);
foreach (DependencyObject child in childs)
{
//analyze if children match the requested type
if (child != null && child is T)
{
yield return (T) child;
}
//recurse tree
foreach (T descendant in FindChildren<T>(child))
{
yield return descendant;
}
}
}
}
请参阅本文全文(在WPF树中查找元素)。
对我来说VisualTreeHelper.GetChildrenCount总是为选项卡控件返回0,我不得不使用此方法代替
public static List<T> ObtenerControles<T>(DependencyObject parent)
where T : DependencyObject
{
List<T> result = new List<T>();
if (parent != null)
{
foreach (var child in LogicalTreeHelper.GetChildren(parent))
{
var childType = child as T;
if (childType != null)
{
result.Add((T)child);
}
foreach (var other in ObtenerControles<T>(child as DependencyObject))
{
result.Add(other);
}
}
}
return result;
}