0

我正在尝试这样,但我只得到第一级文本框。如何查询并获取所有文本框

    IEnumerable<UIElement> textboxes =
         from c in this.LayoutRoot.Children
         where c.GetType() == typeof(TextBox)
         select c;

这是我的xml:

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Canvas x:Name="LayoutRoot" Background="White">
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="160,112,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <TextBox Height="24" HorizontalAlignment="Left" Margin="76,24,0,0" Name="textBox1" VerticalAlignment="Top" Width="196" Text="test message" />
        <CheckBox Canvas.Left="148" Canvas.Top="64" Content="CheckBox" Height="16" Name="checkBox1" Checked="checkBox1_Checked"/>
        <StackPanel Orientation="Vertical">
            <StackPanel Orientation="Horizontal">
                <Grid>
                    <StackPanel Orientation="Vertical">
                        <TextBox Text="test"/>
                        <ComboBox x:Name="combobox" />
                    </StackPanel>
                </Grid>
            </StackPanel>
        </StackPanel>
    </Canvas>
</UserControl>
4

2 回答 2

0
IEnumarable<DependencyObject> AllDescendent(DependencyObject current)
{
    yield return current;
    int n = VisualTreeHelper.GetChildrenCount();
    for (int k = 0; k < n; k ++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(current, k);
        foreach(var descendent in AllDesendent(child))
        {
            yield return descendent;
        }
    }
}

然后

var textboxes = AllDescendent(layoutRoot).OfType<TextBox>();
于 2012-07-23T06:50:52.470 回答
0

您需要使用未内置于 LINQ 中的递归。这是您可以用来启用它的扩展方法:

递归 LINQ 查询示例

于 2011-01-08T02:10:48.913 回答