xamarin - 页面打开时如何在 Xamarin 选择器中设置 SelectedItem
问题描述
我有一个使用 XamarinForms 和 Prism MVVM 的小项目。在设置页面上,我从 Picker 中保存了作者的 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 > OnNavigatingTo 函数中,我调用 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 函数中的分配对我不起作用。
解决方案
从数据库中检索 NoteAuthor 后,您必须通过引用其中一个来设置 SelectedAuthor。Picker 使用引用相等,因此在 GetAuthor 中从数据库中加载另一个作者实例根本不起作用。下面的代码解决了这个问题,它还提高了代码的性能。
NoteAuthors = await // read them from db ...
SelectedAuthor = NoteAuthors.SingleOrDefault(a => a.Id == author_id); // don't load it from database again.
推荐阅读
- confluent-platform - RowSubscriber 如何判断窗口的第一条记录何时到达?
- css - 选择选项在我的控制台中完美运行时无法以我的模态形式工作
- jquery - ASP.NET Core + Antiforgery + jQuery Ajax POST + Nginx - 400 错误请求
- azure-data-explorer - Kusto - 使用解析运算符将字符串字段提取到新列中
- node.js - 如何在 API 网关中设置响应模板以从错误中删除堆栈跟踪?
- python - 从 Python 中的段错误中恢复
- nullpointerexception - 在我的服务集成中,我在实例化另一个服务的类时发现了 NullPointerException
- javascript - TypeError:无法读取 null 的属性“项目”
- python - 如何合并存储在列表中的几个数组
- c# - 如何修复无法从另一个 Thread 访问 Thread 元素的问题