Build UserControl views "dynamically"

1

I try to create a certain number of views depending on a value and add them to the main view, in a StackPanel;

    private void ConstruirFilas(int numFilas)
    {
        for (int i = 1; i < numFilas; i++)
        {
            StackConfiguracion.Children.Add(new ConfigNivel(i));
        }
    }

If I do it this way, the views are created but I do not know how to access the properties or methods of those objects that have been created within the for since they are created "on the fly". Could you somehow access them?

On the other hand, if I create an array of objects ConfigNivel and then try to pass them to the for a runtime error alerting me that I can not pass null values, the code is this;

    private void ConstruirFilas(int numFilas)
    {
        ConfigNivel[] aaa = new ConfigNivel[8];

        for (int i = 1; i < numFilas; i++)
        {
            StackConfiguracion.Children.Add(aaa[i]);
        }
    }
    
asked by Edulon 07.02.2018 в 19:50
source

1 answer

1

You can access the Children of StackConfiguration directly. Using your example, to create them you use this code:

for (int i = 1; i < numFilas; i++)
{
    StackConfiguracion.Children.Add(new ConfigNivel(i));
}

Then, to access them, you can do the following:

var vistas = StackConfiguracion.Children.OfType<ConfigNivel>();

This returns a IEnumerable<ConfigNivel> , which you can then go through with foreach for example:

foreach (var vista in vistas)
{
     //en vista tienes cada una de las vistas que añadiste con anterioridad
     // puedes llamar al método de cada una
     vista.tuMetodo();
}
    
answered by 08.02.2018 / 09:23
source