简体   繁体   中英

xamarin forms: how to make sure that a picker is not null or empty?

Right now the user can skip a picker selection. How to make sure the user selects a selection before going to the next picker? For example if 2nd Picker is empty then it cant move to 3rd picker.

im tried if else statements but I don't know where to put it and there should be a better way to do it perhaps?

You can have a simple logic like this. In each picker, detect the focused event, and then, check if the previous has a value /selectedindex was not changed, then apply your logic / popups, etc.

YourPicker2.Focused += (object sender, EventArgs e) => 
{
    if(YourPicker1.SelectedIndex==-1)
    {
        DisplayAlert("Please fill the XXX picker");
    }

};

Here is a sample for your question.There are there pickers in Xaml :

<Picker x:Name="PickerOne" Title="Select First" TitleColor="Red">
<Picker x:Name="PickerTwo" Title="Select Second" TitleColor="Green" IsEnabled = "False">
<Picker x:Name="PickerThree" Title="Select Three" TitleColor="Blue" IsEnabled = "False">

In ContentPage , setting ItemSource :

var monkeyList = new List<string>();
monkeyList.Add("Baboon");
monkeyList.Add("Capuchin Monkey");
monkeyList.Add("Blue Monkey");
monkeyList.Add("Squirrel Monkey");
monkeyList.Add("Golden Lion Tamarin");
monkeyList.Add("Howler Monkey");
monkeyList.Add("Japanese Macaque");

PickerOne.ItemsSource = monkeyList;
PickerTwo.ItemsSource = monkeyList;
PickerThree.ItemsSource = monkeyList;

and adding SelectedIndexChanged method :

PickerOne.SelectedIndexChanged += PickerOne_SelectedIndexChanged;
PickerTwo.SelectedIndexChanged += PickerTwo_SelectedIndexChanged;


void PickerOne_SelectedIndexChanged(object sender, EventArgs e)
{
  var picker = (Picker)sender;
  int selectedIndex = picker.SelectedIndex;

  if (selectedIndex != -1)
  {
    PickerTwo.IsEnabled = true;
  }else{
    PickerTwo.IsEnabled = false;
  }
}

void PickerTwo_SelectedIndexChanged(object sender, EventArgs e)
{
  var picker = (Picker)sender;
  int selectedIndex = picker.SelectedIndex;

  if (selectedIndex != -1)
  {
    PickerThree.IsEnabled = true;
  }else{
    PickerThree.IsEnabled = false;
  }
}

You should use MVVM pattern and Model binding. So you can check validation against the model rather than each UI control. A simple guide can be foudn here: https://www.codeproject.com/Articles/1274851/Xamarin-Forms-Validations-Made-Simple

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