我正在尝试这样,但我只获得了第一级文本框。如何查询并获取所有文本框
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>
答案 0 :(得分:0)
您需要使用未内置于LINQ中的递归。这是一个可用于启用它的扩展方法:
答案 1 :(得分: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>();