我制作了这个关于使用 Picker 和 MVVM 绑定的简单演示项目。作为项目来源,我使用ObservableCollection 类型的Person。
当用户从 Picker 中选择一项时,下面标签的值/内容会发生变化。请看一下我认为这个项目是您解决问题所需要的。
您没有向我们提供您的全部代码,因此很难看出您可能犯的错误。也许这对你有帮助。
演示:
代码sn-ps:
我的 Person 类如下所示:
public class Person {
public int PersonId { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string FullName { get { return $"{FName} {LName}"; } }
public string Biography { get; set; }
}
我的视图模型:
public class AllPersonsViewModel : INotifyPropertyChanged{
public ObservableCollection<Person> AllPersons { get; set; }
private Person selectedPerson;
public Person SelectedPerson {
get { return selectedPerson; }
set { selectedPerson = value;
OnPropertyChanged();
}
}
public AllPersonsViewModel() {
AllPersons = new ObservableCollection<Person>() {
new Person() {
Biography = "Lorem ipsum person 1",
FName = "Person",
LName = "One",
PersonId = 1,
},
new Person() {
Biography = "Lorem ipsum person 2",
FName = "Person",
LName = "Two",
PersonId = 2,
},
new Person() {
Biography = "Lorem ipsum person 3",
FName = "Person",
LName = "Three",
PersonId = 3,
},
};
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName]string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
我有一个视图使用这个视图模型作为BindingContext
... 和带有Picker 控件的我的页面的 XAML 在这里:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XF.Picker.Demo.Views.PersonsPage">
<ContentPage.Content>
<StackLayout Orientation="Vertical">
<Picker Title="All person"
ItemDisplayBinding="{Binding FullName}"
ItemsSource="{Binding AllPersons}"
SelectedItem="{Binding SelectedPerson}"/>
<!-- Margin just to see picker dropdown and labels at the same time-->
<Label Text="{Binding SelectedPerson.FullName}" Margin="0,80,0,0"/>
<Label Text="{Binding SelectedPerson.Biography}"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
我在github上发布了这个代码项目你可以找到它here