I have an issue related to finding children of a user control. The user control resides in a tab item of a tab control
XAML
<TabControl HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="150">
<TabItem Header="First tab">
<Grid Background="#FFE5E5E5"/>
</TabItem>
<TabItem Header="Tab with stackpanel" x:Name="tabWithStackPanel">
<StackPanel>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
<TextBox></TextBox>
</StackPanel>
</TabItem>
<TabItem Header="Tab with user control" x:Name="tabWithUserControl">
<control:UserControl1/>
</TabItem>
</TabControl>
<Button Height="46" Width="70" Panel.ZIndex="1001" Click="Button_Click">Find</Button>
The method that return the children of a dependency object
public static List<T> FindChildren<T>(DependencyObject parent) where T : DependencyObject
{
if (parent == null) return null;
List<T> children = new List<T>();
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
T childType = child as T;
if (childType == null)
{
children.AddRange(FindChildren<T>(child));
}
else
{
children.Add((T)child);
}
}
return children;
}
So as you see in XAML the second TabItem
contains a StackPanel
which contains some TextBoxes
. The third TabItem
contains a UserControl
which also contains TextBoxes
.
Now when I click the Find button the event handler should do the following
var children1 = Util.FindChildren<TextBox>(tabWithStackPanel.GetValue(TabItem.ContentProperty) as StackPanel);
var children2 = Util.FindChildren<TextBox>(tabWithUserControl.GetValue(TabItem.ContentProperty) as UserControl1);
The issue is that first line returns all the children of the StackPanel
panel, but the second line does not return all the children of the UserControl1
.
I have to select the "Tab with user control" first in order to get all the children of the UserControl1
.
Any clue how to solve the issue?
The non-selected
TabItem
doesn't exist in the Visual tree, but does exist in the Logical tree.Replace your calls to
VisualTreeHelper
with equivalent calls toLogicalTreeHelper