简体   繁体   中英

Xamarin Forms Picker Cascading

I am involved in a project where I am stuck in the following situation: I have a picker (dropdown) where it needs to display a second picker based on first selected item from the first picker (Cascading). Values are dynamic (from Sqlite tables). Here you have my codes:

XAML

 Picker 1
    <Picker x:Name="picker" Title="Select Country" SelectedIndexChanged="OnModeChosen">
    Picker 2
    <Picker x:Name="picker2" Title="Select Regions" IsEnabled="False">

Models

public class Country
        {
          [PrimaryKey]
          Public int CountryId {get;set;}
          public string CountryName {get;set;}

          public Country(){}
        }

        public class Regions
        {
          [PrimaryKey]
          public int RegionsId {get; set;}
          public string RegionsName {get;set;}
          [ForeignKey(typeof(Country))]
          public int CountryId {get;set;}

          public Regions(){}
        }

// Code Behind

private void OnModeChosen(object sender, EventArgs e)
    {
    Picker modePicker = (Picker)sender;
    var mode = picker.SelectedIndex;
    picker2.Items.Clear();

         switch(mode)
         {
           //This is the part I would like dynamic
         }
     }

I would like the handler "OnModeChosen" to work dynamically (any selected value from picker 1 will display the according values of picker 2). By the way, I would appreciate any other approach, as I am interested in having the expected result. Thanks for your support guys. I am working on this for hours and can't find anything worth it on internet.

So this is how I solved it in my project:

  private void OnModeChosen(object sender, EventArgs e)
    {
         Country country = ((Country)(picker.SelectedItem)) // get the country object from  the picker
          picker2.ItemsSource =  GetRegions(country.CountryId ) // call the function to get the regions for that country
          picker2.ItemDisplayBinding = New Binding("RegionsName")
          picker2.SelectedIndex = 0 // not sure why I did this, I think to make sure an item was selected
        stackpicker2.IsVisible = true // make the stack layout visible with the 2nd picker
        picker2.IsEnabled = true;
    }

Hope this helps

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