Search code examples
c#wpfuser-controls

Child UserControl TextBox value in Parent UserControl WPF


I have a parent UserControl that has a Button. On button_click a child UserControl is added into Parent UserControl. That newly added Child UserControl have a TextBox.
Now, Parent UserControl has another Button when clicked i want to get the value of TextBox of child UserControl. How can i get that ?

Plus, let's say the child UserControl added on RunTime are more than 1. Then how can i get TextBox value of all of these child UserControls ?

EDIT and UPDATE !
Child UserControl have this method

    public string GetText()
    {
        return ProductNameBox.Text;
    }  

Parent UserControl have this

    public List<UserControl> UserControlList = new List<UserControl>();

    public void NewProductModule(object sender, RoutedEventArgs e)
    {
            AddProductModule productModules = new AddProductModule();                
            UserControlList.Add(productModules);
    }  

And This method

    private void PreviewPdfFunc(object sender, MouseButtonEventArgs e)
    {
        foreach (UserControl cnt in UserControlList)
        {
            MessageBox.Show(cnt +" Total = " + StackPanelContainer.Children.Count);
        }
    }

Solution

  • First of, add every AddProductModule you create to a list (because you have to store them somewhere)

    List<AddProductModule> AllControls = new List<AddProductModule>();
    AllControls.Add(YourItem);
    

    Second, you have two Options to get the text

    First: Set the button to public

    Second: Create a public method which you can call from your Parent, for example

    public string GetTBText()
    {
        return TextBoxExample.Text;
    }
    

    In the end, to get all Texts, you could

    foreach(AddProductModule item in AllControls)
    {
        string ValueOfTB = item.GetTBText();
    }
    

    EDIT

    There was the Problem, that a wrong object type was in use, which made Problems with my answer. Formerly, the type was not AddProductModule, instead it was UserControl, and before that it was var (which was the main Problem to begin with)

    If you come here, you should now be able to run the code in my answer without a problem