How to get all the textBoxes in the UserControl added into GridView

三世轮回 提交于 2019-12-08 02:29:02

问题


On the Page, I add UserControl into GridView dynamically. So, each UserControl can contain different kind of controls ( TextBox, CheckBox, Radio Button)

say , the name of UserControl is : UserForm.

problem : How to get a collection of control using VisualTreeHelper and check if textBox is empty.

I found a code similiar to this problem and modified it but not working.

I dont know what this means and if this is required?

list.AddRange(AllTextBoxes(child))

Should I use MyList.Select() or MyList.Where() ?


void FindTextBoxes()
{

   List <TextBox> MyList = AllTextBoxes(UserForm);

   var count = MyList.Where(x= > if(string.IsEmptyOrNull(x.Text));

}




List <TextBox> AllTextBoxes(DependencyObject parent)
{
    var list = new List <TextBox>();

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);

        if (child is TextBox)

            list.Add(child as TextBox);

        list.AddRange(AllTextBoxes(child));
    }
    return list;
}



回答1:


Here's what I use.

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    var textBoxes = AllChildren(MyGridView).Where(x => x is TextBox);
}

public IEnumerable<Control> AllChildren(DependencyObject parent)
{
    for (int index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++)
    {
        var child = VisualTreeHelper.GetChild(parent, index);
        if (child is Control)
            yield return child as Control;
        foreach (var item in AllChildren(child))
            yield return item;
    }
}

Best of luck!



来源:https://stackoverflow.com/questions/27333169/how-to-get-all-the-textboxes-in-the-usercontrol-added-into-gridview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!