我在页面上有几个Silverlight控件,并希望查询所有类型为TextBox的控件并使其正常工作.
现在我正在处理的Silverlight表单可以添加更多的TextBox控件.所以当我测试一下TextBox控件是否有值时,我可以这样做:
if (this.TextBox.Control.value.Text() != String.Empty) { // do whatever }
但我宁愿有灵活性,我可以在任何Silverlight表单上使用它,无论我有多少TextBox控件.
关于如何做到这一点的任何想法?
我已经遇到过这个问题,请在此处通知:http://megasnippets.com/en/source-codes/silverlight/Get_all_child_controls_recursively_in_Silverlight
这里有一个通用的方法可以在VisualTree中以递归方式查找所有TextBox:
IEnumerableGetChildrenRecursively(DependencyObject root) { List children = new List (); children.Add(root); for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++) children.AddRange(GetChildrenRecursively(VisualTreeHelper.GetChild(root, i))); return children; }
像这样使用此方法来查找所有TextBox:
var textBoxes = GetChildrenRecursively(LayoutRoot).OfType();
听起来你需要像下面的GetTextBoxes 这样的递归例程:
void Page_Loaded(object sender, RoutedEventArgs e) { // Instantiate a list of TextBoxes ListtextBoxList = new List (); // Call GetTextBoxes function, passing in the root element, // and the empty list of textboxes (LayoutRoot in this example) GetTextBoxes(this.LayoutRoot, textBoxList); // Now textBoxList contains a list of all the text boxes on your page. // Find all the non empty textboxes, and put them into a list. var nonEmptyTextBoxList = textBoxList.Where(txt => txt.Text != string.Empty).ToList(); // Do something with each non empty textbox. nonEmptyTextBoxList.ForEach(txt => Debug.WriteLine(txt.Text)); } private void GetTextBoxes(UIElement uiElement, List textBoxList) { TextBox textBox = uiElement as TextBox; if (textBox != null) { // If the UIElement is a Textbox, add it to the list. textBoxList.Add(textBox); } else { Panel panel = uiElement as Panel; if (panel != null) { // If the UIElement is a panel, then loop through it's children foreach (UIElement child in panel.Children) { GetTextBoxes(child, textBoxList); } } } }
实例化一个空文本框列表.调用GetTextBoxes,传入页面上的根控件(在我的例子中,就是this.LayoutRoot),GetTextBoxes应递归循环遍历该控件后代的每个UI元素,测试它是否是TextBox(添加它)列表)或小组,可能有它自己的后代来递归.
希望有所帮助.:)