首页 > 解决方案 > 页面打开时如何在 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 函数中的分配对我不起作用。

标签: xamarinxamarin.formsprism

解决方案


从数据库中检索 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.

推荐阅读