Set a Picker.SelectedItem on page startup

bifedefrangobifedefrango Member ✭✭
edited April 12 in Xamarin.Forms

I have this piece of code

<Picker x:Name="CategoryPicker" 
ItemsSource="{Binding Categories, Mode=TwoWay}"
SelectedItem="{Binding Path= RequestItem.Category, Mode=TwoWay}" 
Title="Escolha uma Categoria"
ItemDisplayBinding="{Binding Name}"

I'm saving an item, and when I save it, it goes to a list of items... If I want to change one of those items, I need to set the picker to the value stored in RequestItem.Category...
Since I'm binding the SelectedItem property It should automaticaly set the value of it rigth?

I've also tryed to do this on my Page constructor with this
CategoryPicker.SelectedItem = estimate?.Category;
and this
CategoryPicker.SelectedIndex = 0;
If I set a breakpoint rigth after this, CategoryPicker.SelectedIndex is equal to -1... It doesn't change to 0...

None of those seems to work... What am I doing wrong?

Best Answer


  • yogeshwaranmohanyogeshwaranmohan Member ✭✭
    edited April 12

    Are you confirmed when loading the picker the Categories contains any items. If there is no any item then the picker selected item will be -1.

  • bifedefrangobifedefrango Member ✭✭
    edited April 12
    BindingContext = vm = new EstimateRequestAddNewItemViewModel(Navigation, viewModel, estimate);
    vm.GetCategoriesCommand.Execute(null); //---> get the categories
    CategoryPicker.SelectedIndex = 0; //---> CategoryPicker.ItemsSource = null
    SubCategoryPicker.SelectedItem = estimate.SubCategory;

    when the page opens I have the items on Category picker so what can i do to populate CategoryPicker.ItemsSource before page loads?

  • bifedefrangobifedefrango Member ✭✭

    Thanks a lot man! That didn't quite solve the problem, but indeed help! I was able to set the selected index and now it's working... I just need to save the index position and then it will be fine! Thanks man!

  • bifedefrangobifedefrango Member ✭✭

    if anyone has this problem just make sure itemsSource is setted first then the selected Item
    otherwise the application set the selected item of a null context

Sign In or Register to comment.