当页面打开时,如何在Xamarin选择器中设置SelectedItem
我有一个使用XamarinForms和Prism MVVM的小项目。 在设置页面上,我从选择器保存作者ID。 当我返回到设置页面时,我希望默认情况下在选择器中选择该作者 这是我在Xaml中的选择器:当页面打开时,如何在Xamarin选择器中设置SelectedItem,xamarin,xamarin.forms,prism,Xamarin,Xamarin.forms,Prism,我有一个使用XamarinForms和Prism MVVM的小项目。 在设置页面上,我从选择器保存作者ID。 当我返回到设置页面时,我希望默认情况下在选择器中选择该作者 这是我在Xaml中的选择器: <Picker x:Name="authorPicker" Title="Select Author" FontSize="Medium" HorizontalOptions="StartAndExpand" VerticalOptions="Ce
<Picker x:Name="authorPicker" Title="Select Author" FontSize="Medium"
HorizontalOptions="StartAndExpand" VerticalOptions="Center"
ItemsSource="{Binding NoteAuthors}"
ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding SelectedAuthor, Mode=TwoWay}"
Grid.Row="0" Grid.Column="1" />
在ViewModel>OnNavigationTo函数中,我调用GetAuthor函数,该函数根据先前保存的ID返回Author
public async void GetAuthor(int author_id)
{
NewNoteAuthor = await App.Database.GetAuthorById(author_id);
if(NewNoteAuthor != null && NewNoteAuthor.ID > 0)
{
SelectedAuthor = NewNoteAuthor;
}
}
当页面打开时,我如何“跳转”到此作者?GetAuthor函数中的赋值不适用于我。从数据库检索NoteAuthors后,必须通过引用其中一个作者来设置SelectedAuthor。Picker使用引用相等,所以从GetAuthor中的数据库加载另一个author实例根本不起作用。下面的代码解决了这个问题,同时也提高了代码的性能
NoteAuthors = await // read them from db ...
SelectedAuthor = NoteAuthors.SingleOrDefault(a => a.Id == author_id); // don't load it from database again.
从数据库检索NoteAuthors后,必须通过引用其中一个作者来设置SelectedAuthor。Picker使用引用相等,所以从GetAuthor中的数据库加载另一个author实例根本不起作用。下面的代码解决了这个问题,同时也提高了代码的性能
NoteAuthors = await // read them from db ...
SelectedAuthor = NoteAuthors.SingleOrDefault(a => a.Id == author_id); // don't load it from database again.
是否必须将数据列表作为可观察的集合?是否必须将数据列表作为可观察的集合