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

如何将ListView中Entry的Text绑定到与ItemsSource无关的其他模型

ListView条目绑定非ItemsSource关联模型的实现方案

方案1:构造组合视图模型(最推荐,实现最简单)

你可以为列表条目专门构造一个组合的视图模型,同时包含人员姓名和收入存储属性,不需要修改原有数据库模型,绑定逻辑最清晰:

  1. 定义组合模型类
public class PeopleIncomeItem
{
    // 对应数据库存储的人员姓名
    public string Name { get; set; }
    // 用于存储用户输入的收入,对应你需要的新模型属性
    public decimal? Income { get; set; }
    // 可根据需求扩展,比如保留原数据库实体对象
    // public People OriginalPeople { get; set; }
}
  1. 后台代码构造绑定数据源
// 从SQLite查询原有人员数据
var peopleList = conn.Table<People>().ToList();
// 转换为组合视图模型集合
var listSource = peopleList.Select(p => new PeopleIncomeItem
{
    Name = p.name,
    // OriginalPeople = p
}).ToList();
// 赋值给ListView的ItemsSource
Mlist.ItemsSource = listSource;
  1. 修改XAML绑定逻辑
<ListView x:Name="Mlist" Grid.Row="3" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid Padding="5" BackgroundColor="White" RowSpacing="40">
                    <Label HorizontalOptions="Center" Text="{Binding Name}" />
                    <!-- 直接绑定组合模型里的收入属性 -->
                    <Entry Placeholder="type the income" Text="{Binding Income}" />
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

方案2:绑定外部独立模型(无需修改原有ItemsSource)

如果你确实需要将收入数据存在和列表数据源完全独立的模型中,可以通过RelativeSource引用父级上下文来绑定,这里以收入存储在页面级的字典模型为例:

  1. 后台定义独立的收入存储模型
// 页面类中定义全局收入存储字典,Key为人员唯一ID,Value为对应收入
public Dictionary<int, decimal?> UserIncomes { get; set; } = new();

public YourPage()
{
    InitializeComponent();
    // 将页面自身设为BindingContext,方便XAML引用
    BindingContext = this;
    // 原有绑定逻辑不变
    Mlist.ItemsSource = conn.Table<People>().ToList();
}
  1. 修改XAML绑定逻辑
<ListView x:Name="Mlist" Grid.Row="3" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid Padding="5" BackgroundColor="White" RowSpacing="40">
                    <Label HorizontalOptions="Center" Text="{Binding name}" />
                    <!-- 通过RelativeSource绑定页面级的收入字典,用当前条目的人员ID做索引 -->
                    <Entry Placeholder="type the income" 
                           Text="{Binding Source={RelativeSource AncestorType={x:Type ContentPage}}, 
                           Path=BindingContext.UserIncomes[{Binding id}]}" />
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

注意事项

  • 如果需要UI和数据双向实时更新,你的模型类需要实现INotifyPropertyChanged接口,列表集合可替换为ObservableCollection<T>
  • 方案2要求你的People类存在唯一标识字段(如id)作为字典的Key,否则无法匹配人员和对应收入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 08:36:04