0
votes

For my Xamarin Forms app I'm using a picker to select subcategories of a quiz category.

<Picker x:Name="subCategory" Title="SUBCategory" ItemsSource="{Binding SubCategories}" ItemDisplayBinding="{Binding Subcategory}" SelectedItem="{Binding selSubCategories, Mode=TwoWay}" />

By default the text of the picker the title SUBCategory, but I want to change this to one of the items which I get from an api call.

At first, I loaded the ItemSource from the view and tried to set the SelectedItem that, but without any success.

Then I changed it to a ViewModel to load the data and set the selected item, based on different websites. Items are loaded correctly from the ViewModel, but with the SelectedItem still no success. I also tried with the SelectedIndex which didn't work, but I prefer the SelectedItem, because this is the value I got literally.

public class QuizPageViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    CheetahApi api = new CheetahApi();

    public QuizPageViewModel()
    {
        GetSubCategories();
    }

    SubCategory countries =
        new SubCategory() { Subcategory="Olympische Spelen"}
    ;
    public SubCategory selSubCategories;

    private ObservableCollection<SubCategory> _subCategories = new ObservableCollection<SubCategory>();
    public ObservableCollection<SubCategory> SubCategories
    {
        get { return _subCategories; }
        set
        {
            _subCategories = value;
            OnPropertyChanged(nameof(SubCategories));
        }
    }

    private async void GetSubCategories()
    {
        var subCat = await api.GetSubCategories("sport");
        foreach (var sub in subCat)
        {
            SubCategories.Add(sub);
        }
        selSubCategories = subCat.FirstOrDefault(a => a.Subcategory == "Olympische Spelen");
    }

    protected virtual void OnPropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Model

public class SubCategory
{
    public int Id { get; set; }
    public string Category { get; set; }
    public string Subcategory { get; set; }
}

Does anyone has an idea how to set the default text of a picker to one of the items in the Source?

1

1 Answers

2
votes

You need to implement OnPropertyChanged for the SelectedItem field, like:

private SubCategory _selSubCategories;
public SubCategory selSubCategories
{
    get { return _selSubCategories; }
    set
    {
        _selSubCategories = value;
        OnPropertyChanged(nameof(selSubCategories));
    }
}