【问题标题】:How to set SelectedItem in Xamarin picker when page opens页面打开时如何在 Xamarin 选择器中设置 SelectedItem
【发布时间】:2018-07-26 14:24:20
【问题描述】:

我有一个使用 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" />

When Author is selected I got this in ViewModel and it works fine:

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

在 ViewModel > OnNavigatingTo 函数中,我调用 GetAuthor 函数,该函数根据之前保存的 ID 返回作者。

    public async void GetAuthor(int author_id)
    {
        NewNoteAuthor = await App.Database.GetAuthorById(author_id);
        if(NewNoteAuthor != null && NewNoteAuthor.ID > 0)
        {
            SelectedAuthor = NewNoteAuthor;
        }
    }

页面打开时如何“跳转”到该作者? GetAuthor 函数中的赋值对我不起作用。

【问题讨论】:

    标签: xamarin xamarin.forms prism


    【解决方案1】:

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

    【讨论】:

    • 是否必须将数据列表设为可观察集合
    猜你喜欢
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多