且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 UserControl 中的所有文本框添加到 GridView

更新时间:2023-02-20 15:55:37

这是我使用的.

void MainPage_Loaded(object sender, RoutedEventArgs e){var textBoxes = AllChildren(MyGridView).Where(x => x is TextBox);}公共 IEnumerable<Control>AllChildren(DependencyObject parent){for (int index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++){var child = VisualTreeHelper.GetChild(parent, index);如果(孩子是控制)yield return child 作为 Control;foreach (AllChildren(child) 中的 var 项目)收益率返回项;}}

祝你好运!

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;
}


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!