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>(); 
    
  • 相关阅读:
    2018年你需要知道的13个JavaScript工具库
    JavaScript一团乱,这是好事
    5大JavaScript前端框架简介
    大型Vuex应用程序的目录结构
    Github被微软收购,这里整理了16个替代品
    如何使用@vue/cli 3.0在npm上创建,发布和使用你自己的Vue.js组件库
    TensorFlow入门教程
    想成为顶级开发者吗?亲自动手实现经典案例
    2018年最值得关注的30个Vue开源项目
    SQL Server 合并复制遇到identity range check报错的解决 (转载)
  • 原文地址:https://www.cnblogs.com/zhangq723/p/1710246.html
Copyright © 2011-2022 走看看