You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何跟踪代码添加的View元素并移除对应Entry的文本值?

问题解决方案

原代码核心问题

  • entryValues和stackList是方法局部变量,每次调用AddLayout都会重新创建,之前的条目数据完全无法保留
  • Add按钮点击时添加的是同一个horizontalLayout实例,导致界面重复添加同一布局,事件绑定逻辑彻底混乱
  • Remove按钮的索引操作逻辑错误:counter--后再执行RemoveAt(counter),会误删上一个位置的条目,而非当前要删除的目标
  • Entry的Unfocused事件每次都往列表新增值,而非更新对应条目的内容,导致列表数据与实际Entry内容不匹配

修复后的完整代码

首先将需要持久化的变量提升为类成员变量:

// 类级别变量,保证多次调用AddLayout时数据不丢失
private int _counter = 0;
private List<string> _entryValues = new List<string>();
private List<StackLayout> _stackList = new List<StackLayout>();

然后修改AddLayout方法:

private void AddLayout()
{
    // 每次创建全新的布局实例,避免复用同一控件
    var horizontalLayout = new StackLayout()
    {
        Orientation = StackOrientation.Horizontal,
        Children =
        {
            new Entry(),
            new Button { Text = "Add" },
            new Button { Text = "Remove" }
        }
    };

    // 提前为新Entry在列表中预留位置(空字符串)
    _entryValues.Add(string.Empty);
    // 捕获当前条目的索引,绑定到后续事件中
    int currentIndex = _counter;

    // 获取当前布局内的控件实例
    var entry = horizontalLayout.Children.OfType<Entry>().FirstOrDefault();
    var addBtn = horizontalLayout.Children.OfType<Button>().FirstOrDefault();
    var removeBtn = horizontalLayout.Children.OfType<Button>().ElementAt(1);

    // Entry失焦时,更新对应索引的列表值
    entry.Unfocused += (o, ev) =>
    {
        if (entry != null && currentIndex < _entryValues.Count)
        {
            _entryValues[currentIndex] = entry.Text;
        }
    };

    // Add按钮点击:创建新的条目
    addBtn.Clicked += (o, ev) =>
    {
        AddLayout();
    };

    // Remove按钮点击:精准移除对应条目
    removeBtn.Clicked += (o, ev) =>
    {
        // 1. 从界面容器移除布局
        container.Children.Remove(horizontalLayout);
        // 2. 移除列表中对应的条目
        _stackList.RemoveAt(currentIndex);
        _entryValues.RemoveAt(currentIndex);
        // 3. 更新计数器
        _counter--;
    };

    // 将新布局添加到容器和列表
    container.Children.Add(horizontalLayout);
    _stackList.Add(horizontalLayout);
    _counter++;
}

关键改动说明

  1. 类成员变量替代局部变量:确保所有条目数据在多次AddLayout调用中持续保留
  2. 每次创建新布局实例:避免重复添加同一控件导致的逻辑混乱
  3. 绑定当前条目索引:用currentIndex捕获每个条目的创建时索引,保证Remove操作能精准定位到对应列表项
  4. 更新而非新增列表值:Entry失焦时直接更新对应索引的_entryValues内容,保证列表与Entry内容完全同步
  5. 修正Remove逻辑:先移除界面布局,再删除列表对应项,最后更新计数器,避免索引越界或误删

修复后,点击Remove按钮即可精准删除_entryValues中对应条目的文本值,后续可直接使用_entryValues将数据保存到数据库。

内容的提问来源于stack exchange,提问作者Costas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:53:22