【问题标题】:How can I find an UIElement using Linq?如何使用 Linq 找到 UIElement?
【发布时间】:2013-09-03 11:04:39
【问题描述】:

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

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

这是我的 xaml:

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

【问题讨论】:

    标签: silverlight linq-to-objects uielement


    【解决方案1】:
    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>();
    

    【讨论】:

      【解决方案2】:

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

      Recursive LINQ Query Example

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-10
        • 1970-01-01
        • 1970-01-01
        • 2010-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多