简体   繁体   中英

After dynamically creating fields, via Code Behind, How to retrieve the value passed by the user?

I have a place reserved for my Xaml where I will create several fields according to a list coming from the ViewModel.

<StackLayout x:Name="hAcumulativas"/>

Going through the list using the function below I have the fields added to the StackLayout pasted on the screen:

foreach (var item in _vm.ListaTipoHora)
{
    if (item.Acumula == "S")
        IncluirFilhosHAcumulativas(item.Descricao, string.Empty);
    if (item.Acumula == "N")
        IncluirFilhosHNaoAcumulativas(item.Descricao, string.Empty);
}  

private void IncluirFilhosHAcumulativas(string label, string entry)
{
    hAcumulativas.Children.Add(new Label
    {
        Text = label,                
        FontAttributes = FontAttributes.Bold,

    });
    hAcumulativas.Children.Add(new Entry
    {
        Text = entry ,
        Placeholder = "Informe Hodômetro/Horímetro",
        HorizontalOptions = LayoutOptions.CenterAndExpand,
        Keyboard = Keyboard.Numeric
    });
}

I have a save button on the screen, which wants to go through the created fields, since when creating it, there was no Binding at any time.

I'm literally stuck at this point, how to retrieve the values ​​entered by the user? I want to assemble a list and return it to the ViewModel.

You can loop through your stack layout's children and inspect the values of the entries. Something like:

foreach (var item in hAcumulativas.Children)
{
    if (item is Entry entry)
    {
        var thing = entry.Text;
    }
}

Andrew's answer shows the basic technique.

If you need to know exactly which controls were created by your functions, then maintain a list:

private List<Entry> AcumulativasEntries;
...

AcumulativasEntries = new List<Entry>();
foreach (var item in _vm.ListaTipoHora)
{
    if (item.Acumula == "S")
        IncluirFilhosHAcumulativas(item.Descricao, string.Empty);
    if (item.Acumula == "N")
        IncluirFilhosHNaoAcumulativas(item.Descricao, string.Empty);
}  
...

private void IncluirFilhosHAcumulativas(string label, string entry)
{
    ...
    var entry = new Entry{ ... };
    AcumulativaEntries.Add(entry);
    hAcumulativas.Children.Add(entry);
}

Retrieve values by iterating over the list:

foreach (var entry in AcumulativaEntries)
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM