如何使用对象实现ItemsSource绑定?绑定失败显示类名求助
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

