WPF: How to create Multiple instances of a UserControl inside a for loop with different name?

c#, user-controls, windows, wpf

Solution

just use the Name property like this:

        StackPanel sp = new StackPanel();
        for (int i = 0; i < 5; i++)
        {
            UserControl uc = new UserControl();
            uc.Name = "name"+i; // add your name here
            sp.Children.Add(uc);
        }

EDIT

to answer your question in the comment how to get the Control

        var list = sp.Children.Cast<UserControl>();             // now we are able to use Linq
        var sublist = list.Where(item => item.Name == "name1"); // searching for all UserControl with the Name "name1"
        var uControl = sublist.FirstOrDefault();                // will result inyour UserControl or null

        //same as above just in one line
        var uControl2 = sp.Children.Cast<UserControl>().Where(item => item.Name == "name2").FirstOrDefault();

Problem

I am creating a WPF window, inside which I am creating multiple instances of a UserControl. I am using a for loop to create a new instances of the UserControl, how can I give different name to the UserControlinstance? This is what I am doing: ``` for(i=0; i<5; i++) { MyUserControl <name> = new MyUserControl (); /*code to change the properties of usercontrol*/ SomeStackPanel.Children.Add(<name>); } ```

Original source