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

如何使用对象实现ItemsSource绑定?绑定失败显示类名求助

Fixing XAML Picker ItemsSource Binding Issue

Let's break down and fix your binding problem step by step:

1. You're Binding to the Wrong Property

Right now, your Picker's ItemsSource is bound to City—but City is a single string property on your Class object. Picker needs a collection of items (like your list of Class instances) to display options.

First, make sure you have a public collection property in your binding context (either your page code-behind or a view model):

// In your page/view model
public List<Class> CityCollection { get; set; }

Then initialize it correctly (fixing the type mismatch in your original code—you can't add Class instances to a List<AddInfo> unless AddInfo wraps Class):

CityCollection = new List<Class>
{
    new Class { City = "West Amman" },
    new Class { City = "East Amman" },
    new Class { City = "Ajloun" }
};

Update your XAML to bind to this collection:

<Picker ItemsSource="{Binding CityCollection}" x:Name="selectCity" />

2. Tell Picker Which Property to Display

Even if you bind to the correct collection, Picker will default to calling ToString() on each Class instance (which outputs the full class name you're seeing). To show the City value instead, set the DisplayMemberPath property:

<Picker ItemsSource="{Binding CityCollection}"
        DisplayMemberPath="City"
        x:Name="selectCity" />

3. Verify Your Binding Context is Set

Don't forget to ensure your page's BindingContext points to the object containing CityCollection. For example, in your page constructor:

public YourPage()
{
    InitializeComponent();
    BindingContext = this; // If CityCollection is in the page code-behind
    // Or use a view model: BindingContext = new YourViewModel();
}

Quick Note on Type Mismatch

In your original code, you tried adding Class instances to a List<AddInfo>—this will cause a compile error unless AddInfo inherits from Class or you're using an implicit conversion. Double-check your class definitions to make sure your collection type matches the items you're adding.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:43:33