zoukankan      html  css  js  c++  java
  • 获得页面下所有的控件

    Generic method to find all TextBox controls in Silverlight

    void Page_Loaded(object sender, RoutedEventArgs e) 
    { 
        // Instantiate a list of TextBoxes 
        List<TextBox> textBoxList = new List<TextBox>(); 
     
        // 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<TextBox> 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); 
                    } 
            } 
        } 
    } 
    

    Instantiate an empty list of TextBoxes. Call GetTextBoxes, passing in the root control on your page (in my case, that's this.LayoutRoot), and GetTextBoxes should recursively loop through every UI element that is a descendant of that control, testing to see if it's either a TextBox (add it to the list), or a panel, that might have descendants of it's own to recurse through.

    还有其它的方法,如下:

    IEnumerable<DependencyObject> GetChildsRecursive(DependencyObject root) 
    { 
        List<DependencyObject> elts = new List<DependencyObject>(); 
        elts.Add(root); 
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++) 
            elts.AddRange(GetChildsRecursive(VisualTreeHelper.GetChild(root, i))); 
     
        return elts; 
    } 
    

    Use this method like this to find all TextBoxes:

    var textBoxes = GetChildsRecursive(LayoutRoot).OfType<TextBox>(); 
    
  • 相关阅读:
    币值转换
    抓老鼠啊!亏了还是赚了
    打印沙漏
    秋季学习总结
    记忆中最深刻的三位老师
    自我介绍
    docker 安装redis 和 mysql
    centos 安装docker
    celery的简单使用
    django redis配置和简单使用
  • 原文地址:https://www.cnblogs.com/zhangq723/p/1710246.html
Copyright © 2011-2022 走看看