i want to get a list with all elements of my current usercontrol. Not only the one in the LogicalTree, ALL elements inside the defined and used datatemplates in the usercontrol.
When iam iterating threw the VisualTree it dont have VisualTree items inside the ContentControl. I thought the VisualTree contains all Elements?
So at the end i need the TextBox and the Button inside the DataTemplate in my List. But i dont know the x:Name of the elements.
Can somebody help?
<UserControl
x:Class="DataTemplate.Test"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid x:Name="LayoutRoot">
<ContentControl>
<ContentControl.ContentTemplate>
<DataTemplate>
<Grid VerticalAlignment="Stretch">
<Button x:Name="btn_1" />
<TextBlock x:Name="tb_1" />
</Grid>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
</Grid>
</UserControl>
In code i iterate threw it when UserControl.Loaded event is fired...
public void OnUserControlLoaded(object sender, EventArgs e)
{
BindChildren(LayoutRoot);
}
List<object> list = new List<object>();
private void BindChildren(object target) {
try
{
var count = VisualTreeHelper.GetChildrenCount(target as FrameworkElement);
if(count < 1)
{
foreach (var child in LogicalTreeHelper.GetChildren(_currentElement))
{
list.Add(child);
BindChildren(child);
}
}
else
{
for (int i = 0; i < count; i++)
{
list.Add(VisualTreeHelper.GetChild(target as FrameworkElement, i));
BindChildren(VisualTreeHelper.GetChild(target as FrameworkElement, i));
}
}
}
catch (InvalidCastException exc)
{
throw;
}
}