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>(); 
    
  • 相关阅读:
    对"对DllRegisterServer的调用失败,错误代码为0x8007005"的解决办法
    Struts FileUpload 异常处理之Processing of multipart/formdata request failed.
    Java设计模式之简单工厂模式(转载)
    [转]VS 2008 中文"试用版"变"正式版"方法
    XP系统中多用户,自动登陆(一)
    常见Flash无法播放现象处理
    [转]顺利迈出职业成功的第一步
    VS2005的BUG:Cannot convert type 'ASP.login_aspx' to 'System.Web.UI.WebControls.Login'
    OO设计原则
    ASPX页面生成HTML的方法
  • 原文地址:https://www.cnblogs.com/zhangq723/p/1710246.html
Copyright © 2011-2022 走看看