WPF how do I create a textbox dynamically and find the textbox on a button click?

后端 未结 5 892
不思量自难忘°
不思量自难忘° 2021-02-04 04:19

I am creating a TextBox and a Button dynamically using the following code:

Button btnClickMe = new Button();
btnClickMe.Content = \"Cli         


        
5条回答
  •  灰色年华
    2021-02-04 04:23

    If you want to do a comprehensive search through the visual tree of controls, you can use the VisualTreeHelper class.

    Use the following code to iterate through all of the visual children of a control:

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parentObj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(parent, i);
    
        if (child is TextBox)
            // Do something
    }
    

    If you want to search down into the tree, you will want to perform this loop recursively, like so:

    public delegate void TextBoxOperation(TextBox box);
    
    public bool SearchChildren(DependencyObject parent, TextBoxOperation op)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
    
            TextBox box = child as TextBox;
    
            if (box != null)
            {
                op.Invoke(box);
                return true;
            }
    
            bool found = SearchChildren(child, op);
    
            if (found)
                return true;
        }
    }
    

提交回复
热议问题