结构:
for (int i = 0; i < (int)NudLengtht; i++)
{
if (!Byte.TryParse(((TextBox)GrpMessage.Controls.Find("TG_TxtData" + i.ToString(), true)[0]).Text, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out datat[i]))
AddMessage(LstStatus, "Error converting data to send:" + ((TextBox)GrpMessage.Controls.Find("TG_TxtData" + i.ToString(), true)[0]).Text);
}
VisualTreeHelper
类和递归方法来枚举特定类型的所有子级:
IEnumerable<TextBox> textBoxesInGroupBox = FindVisualChildren<TextBox>(theGroupBox);
...
private static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj == null)
yield return (T)Enumerable.Empty<T>();
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child == null)
continue;
if (child is T t)
yield return t;
foreach (T childOfChild in FindVisualChildren<T>(child))
yield return childOfChild;
}
}
示例 XAML 标记:
<GroupBox x:Name="theGroupBox">
<Grid>
<Grid>
<StackPanel>
<TextBox Text="a" />
<TextBox Text="b" />
<TextBox Text="c" />
</StackPanel>
</Grid>
</Grid>
</GroupBox>