1

我想获得一个包含我当前用户控件的所有元素的列表。不仅LogicalTree中的一个,用户控件中定义和使用的数据模板中的所有元素。

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

所以最后我需要在我的列表中的 DataTemplate 中的 TextBox 和 Button。但我不知道元素的 x:Name。

有人可以帮忙吗?

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

在代码中,当 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;
        }
    }
4

0 回答 0