如何在页面打开时在Xamarin选择器中设置SelectedItem



我有一个使用XamarinForms和Prism MVVM的小项目。在设置页面上,我从选取器保存作者的ID。当我返回到设置页面时,我希望在选择器中默认选择"作者"。

这是我在Xaml:中的选取器

<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中得到了这个,它运行良好:

private NoteAuthor _selectedAuthor;
public NoteAuthor SelectedAuthor
{
get { return _selectedAuthor; }
set
{   if (_selectedAuthor != value)
{
SetProperty(ref _selectedAuthor, value);
}
}
}

在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.

最新更新