简体   繁体   中英

xamarin forms picker set selected item

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?

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));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM