Tuesday, March 15, 2011

How do I dynamically create multiple controls in Silverlight?

I know how to create a list of Controls and add new instances of them to it:

private List<FirstCircleControl> Circles = new List<FirstCircleControl>();
FirstCircleControl mc = new FirstCircleControl();
Circles.Add(mc);

I want to add a whole bunch of "FirstCircleControls". How would I add 10 controls to my list? I want to be able to "create" and then "add" them to the list using a loop.

From stackoverflow
  • I wonder why you might need to create them all at once and then add them to the list, but here's a solution:

    Enumerable.Range(0, 10)
              .Select(x => new FirstCircleControl())
              .ToList()                        // Forces creation of controls.
              .ForEach(x => Circles.Add(x));   // Adds them to the list.
    
    Ry : Thanks Mehrdad. Enumerable looks super handy.

0 comments:

Post a Comment