Bodega Pangal
Bodega Pangal

Reputation: 141

How to recover the ID of a Picker in Xamarin

You have a Picker in Xamarin that displays the name of certain Fabricantes, as follows

enter image description here

this picker is filled by passing an ObservableCollection of the FABRICANTES object

Fabricantes.CS:

 public class Fabricante
    {
        [JsonProperty(PropertyName = "id")]
        public int  Id { get; set; }

        [JsonProperty(PropertyName = "name")]
        public string Name { get; set; }
    }

FiltrosView.XAML:

 <Picker Title="Seleccione Fabricante"               
                Margin="15,5,15,5"
                HorizontalOptions="FillAndExpand"
                ItemsSource="{Binding Fabricantes, Mode=TwoWay}"
                ItemDisplayBinding="{Binding Name}"
                SelectedItem="{Binding Id}"
                SelectedIndex="{Binding Id}">         
        </Picker>

How do I fill the Picker? Here I declare the list and the property that will capture the ID of the picker, to open the list in the picker, I will cast the object that arrives from an API and will fill the Observable collection and then bindarla in sight, it WORKS!

FiltrosViewModel.CS:

      public ObservableCollection<Fabricante> Fabricantes { get; set; }

       public int IdSustancia
        {
            get
            {
                return idSustancia;
            }
            set
            {
                if (idSustancia != value)
                {
                    idSustancia = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IdSustancia)));
                }
            }
        }

     var response = await apiService.GetList<Fabricante>(urlService, param);

        var list = (List<Fabricante>)response.Result;
        Fabricantes.Clear();

        foreach (var item in list)
        {
           Fabricantes.Add(item);
        }

But, since I capture the ID (int) of the value that the user entered (string), can this be done in xamarin? I would like to be able to capture the value of the ID of the picker in the property IdSubstance declared previously, how to do it? any help for me?

Upvotes: 0

Views: 1722

Answers (2)

Daniel Cunha
Daniel Cunha

Reputation: 676

The best way of doing that is binding the selected index of the picker. In your XAML code, add the following line to your picker:

SelectedIndex={Binding IdSustancia, Mode=TwoWay}

So, when index != -1 (initial value), you can get Fabricante's ID in your ObservableCollection, accessing Fabricantes[IdSustancia].

Upvotes: 1

Jason
Jason

Reputation: 89102

use the SelectedItem property

SelectedItem="{Binding IdSustancia}"

however, for this to work you need to bind it to a property of type Fabricante.

Upvotes: 0

Related Questions