0

I want to get all control's id of silverlight page. So I want to iterate through all controls inside xaml page. For this I have used following code:

 private List<UIElement> GetElement(UIElement parent, Type targetType)
    {
        List<UIElement> items = new List<UIElement>();
        int count = VisualTreeHelper.GetChildrenCount(parent);
        if (count > 0)
        {
            for (int i = 0; i < count; i++)
            {
                UIElement child = (UIElement)VisualTreeHelper.GetChild(parent, i);
                if (child.GetType() == targetType)
                {
                    items.Add(child);
                }
            }
        }
        return items;
    }

and I call above function on my button click event as below.

    List<UIElement> lsttexts = GetElement(LayoutRoot, typeof(System.Windows.Controls.SLFramework.UniTextBox));
        List<UIElement> lstlabels = GetElement(LayoutRoot, typeof(TextBlock));
        List<UIElement> lstbtn = GetElement(LayoutRoot, typeof(Button));
        List<UIElement> lstcombo = GetElement(LayoutRoot, typeof(ComboBox));
        List<UIElement> lstStackpanel = GetElement(LayoutRoot, typeof(StackPanel));

Demo Example of my page:

  <TextBlock Text="Name : " Grid.Row="0" Grid.Column="0"  HorizontalAlignment="Left" VerticalAlignment="Center" />
    <StackPanel x:Name="stkpnl"  Grid.Row="0" Grid.Column="1" Orientation="Vertical">
        <StackPanel x:Name="childpanel1" Orientation="Horizontal">
            <TextBlock x:Name="lbl1" Text="Name : "  HorizontalAlignment="Left" VerticalAlignment="Center" />
            <TextBox x:Name="txt1" Text="=test1"></TextBox>
        </StackPanel>
        <StackPanel x:Name="childpanel11" Orientation="Horizontal">
            <TextBlock x:Name="lbl11" Text="Name : "  HorizontalAlignment="Left" VerticalAlignment="Center" />
            <TextBox x:Name="txt11" Text="=test11"></TextBox>
        </StackPanel>
    </StackPanel>

It get all textbol and textbox outside the satckpanel, listitem and tab control.

But I want to get all control of page includiing which are inside TabControl, statckpanel and Listitem.

Thanks

3
  • I think you need to call GetElement() recursively. Maybe this will help: stackoverflow.com/questions/974598/…
    – Number8
    Commented Oct 11, 2013 at 12:11
  • Thanks for reply.I have already done this but there is problem with TabControl.I can not find element inside tabcontrol (tabitem) while recursively.
    – Hitesh
    Commented Oct 11, 2013 at 12:17
  • For a TabControl, you need to enumerate the ItemCollection Items property of the TabControl.
    – Number8
    Commented Oct 11, 2013 at 13:46

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.