我想获得一个包含当前usercontrol的所有元素的列表 . 不仅是LogicalTree中的一个,在usercontrol中定义和使用的datatemplate中的所有元素 .

当iam迭代抛出VisualTree时,它在ContentControl中没有VisualTree项 . 我认为VisualTree包含所有元素?

所以最后我需要我的List中的DataTemplate中的TextBox和Button . 但我不知道x:元素的名称 .

有人可以帮忙吗?

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

在代码i迭代时,当UserControl.Loaded事件被触发时抛出它...

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