XAML 动态创建字段后,通过代码隐藏,如何检索用户传递的值?

2eafrhcq  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(109)

我为我的Xaml保留了一个位置,在那里我将根据来自ViewModel的列表创建几个字段。

<StackLayout x:Name="hAcumulativas"/>

使用下面的函数浏览列表,我将字段添加到屏幕上粘贴的StackLayout中:
第一次
我在屏幕上有一个保存按钮,它想要通过创建的字段,因为当创建它时,在任何时候都没有绑定。
我真的在这一点上卡住了,如何检索值 我想组装一个列表并将其返回给ViewModel。

vcudknz3

vcudknz31#

你可以循环遍历堆栈布局的子元素,并检查条目的值,比如:

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

jv2fixgn2#

安德鲁的回答显示了基本的技巧。
如果您需要确切地知道哪些控件是由您的函数创建的,那么请维护一个列表:

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);
}

通过遍历列表来检索值:

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

相关问题