0

Silverlight ページのすべてのコントロールの ID を取得したい。したがって、xaml ページ内のすべてのコントロールを反復処理したいと考えています。このために、次のコードを使用しました。

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

以下のように、ボタンクリックイベントで上記の関数を呼び出します。

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

私のページのデモ例:

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

satckpanel、listitem、およびタブ コントロールの外側にあるすべての textbol と textbox を取得します。

しかし、TabControl、statckpanel、および Listitem 内にあるページを含むすべてのコントロールを取得したいと考えています。

ありがとう

4

0 に答える 0