页面打开时如何在 Xamarin 选择器中设置 SelectedItem
How to set SelectedItem in Xamarin picker when page opens
我有一个使用 XamarinForms 和 Prism MVVM 的小项目。
在设置页面上,我从选择器中保存作者 ID。
当我 return 进入设置页面时,我希望在选择器中默认选择该作者。
这是我在 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" />
选择 Author 后,我在 ViewModel 中得到了它,它工作正常:
private NoteAuthor _selectedAuthor;
public NoteAuthor SelectedAuthor
{
get { return _selectedAuthor; }
set
{ if (_selectedAuthor != value)
{
SetProperty(ref _selectedAuthor, value);
}
}
}
在 ViewModel > OnNavigatingTo 函数中,我调用了 GetAuthor 函数,该函数 returns Author 基于之前保存的 ID。
public async void GetAuthor(int author_id)
{
NewNoteAuthor = await App.Database.GetAuthorById(author_id);
if(NewNoteAuthor != null && NewNoteAuthor.ID > 0)
{
SelectedAuthor = NewNoteAuthor;
}
}
如何在页面打开时向该作者 "jump"? GetAuthor 函数中的赋值对我不起作用。
从数据库中检索到 NoteAuthors 后,您必须通过引用其中之一来设置 SelectedAuthor。 Picker 使用引用相等性,因此在 GetAuthor 中从数据库加载作者的另一个实例根本不起作用。下面的代码解决了这个问题,同时也提高了代码的性能。
NoteAuthors = await // read them from db ...
SelectedAuthor = NoteAuthors.SingleOrDefault(a => a.Id == author_id); // don't load it from database again.
我有一个使用 XamarinForms 和 Prism MVVM 的小项目。 在设置页面上,我从选择器中保存作者 ID。 当我 return 进入设置页面时,我希望在选择器中默认选择该作者。
这是我在 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" />
选择 Author 后,我在 ViewModel 中得到了它,它工作正常:
private NoteAuthor _selectedAuthor;
public NoteAuthor SelectedAuthor
{
get { return _selectedAuthor; }
set
{ if (_selectedAuthor != value)
{
SetProperty(ref _selectedAuthor, value);
}
}
}
在 ViewModel > OnNavigatingTo 函数中,我调用了 GetAuthor 函数,该函数 returns Author 基于之前保存的 ID。
public async void GetAuthor(int author_id)
{
NewNoteAuthor = await App.Database.GetAuthorById(author_id);
if(NewNoteAuthor != null && NewNoteAuthor.ID > 0)
{
SelectedAuthor = NewNoteAuthor;
}
}
如何在页面打开时向该作者 "jump"? GetAuthor 函数中的赋值对我不起作用。
从数据库中检索到 NoteAuthors 后,您必须通过引用其中之一来设置 SelectedAuthor。 Picker 使用引用相等性,因此在 GetAuthor 中从数据库加载作者的另一个实例根本不起作用。下面的代码解决了这个问题,同时也提高了代码的性能。
NoteAuthors = await // read them from db ...
SelectedAuthor = NoteAuthors.SingleOrDefault(a => a.Id == author_id); // don't load it from database again.