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

.NET Maui:非MVC场景下如何用C#手动为Picker绑定Location对象列表

Picker绑定Location集合实现显示名称与获取ID的解决方案

关于List转IList的说明

List<Location>本身就实现了IList<Location>接口,不需要额外转换,直接将你的集合赋值给Picker的数据源即可。

实现步骤

  1. 设置Picker显示LocationName

    • 将从数据库获取的List<Location>集合直接赋值给Picker的ItemsSource属性
    • 通过ItemDisplayBinding指定显示的属性为LocationName,让Picker渲染每个Location的名称
  2. 选中时获取对应的LocationID

    • 监听Picker的SelectedIndexChanged事件,在事件处理逻辑中,将SelectedItem转换为Location类型,直接读取其LocationID属性

代码示例

// 假设已从数据库获取List<Location> locations集合
Picker picker = new Picker();
picker.ItemsSource = locations;
// 指定显示的字段为LocationName
picker.ItemDisplayBinding = new Binding("LocationName");

// 处理选中变更事件
picker.SelectedIndexChanged += (s, e) =>
{
    if (picker.SelectedItem is Location selectedLoc)
    {
        int selectedId = selectedLoc.LocationID;
        // 这里写你拿到ID后的业务逻辑
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 04:52:03