简体   繁体   中英

xamarin forms clear picker selection

I am new to Xamarin along with c# and xaml so this has been quite a learning experience. I am trying to do what I thought would be a simple task (clear a picker selection), but it has proven to become quite a challenge.

Desired functionality: a page with a picker selection, make a selection, save the selection to a variable, move to a different page and then clear the selection made so when going back to the first page there is not a selection made.

I've tried using picker.Items.Clear() and setting the SelectedIndex = -1 but I have consistently gotten the OutOfRangeException. I tried this post but couldn't get any options working: How to clear picker if It is selected in xamarin forms?

I don't want to set the picker to the first option, I want it to be empty so the picker title is displayed which is how it works when it first runs but when I make a selection and move to the next page, when I go back, my initial selection is still made.

Hopefully that all makes sense what I'm trying to achieve. Below is my basic code, any help or direction would be greatly appreciated.

MainPage.xaml:

<StackLayout>
        <Label Text="Select an option:" 
            VerticalOptions="Start" 
            HorizontalOptions="Start" 
        />

        <Picker x:Name="OptionSelect"
            Title="Click to Select"
            SelectedIndexChanged="OptionSelect_OnSelectedIndexChanged"
        />      
</StackLayout>

MainPage.xaml.cs:

    public MainPage()
    {
        InitializeComponent();

        OptionSelect.Items.Add("Option 1");
        OptionSelect.Items.Add("Option 2");
        OptionSelect.Items.Add("Option 3");
    }

    public void OptionSelect_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        var option = OptionSelect.Items[OptionSelect.SelectedIndex];

        //OptionSelect.Items.Clear();
        //OptionSelect.Items.Add("Option 1");
        //OptionSelect.Items.Add("Option 2");
        //OptionSelect.Items.Add("Option 3");

        //OptionSelect.SelectedIndex = -1;

        Navigation.PushAsync(new Page1());
    }

clear picker selection?

Set the SelectedItem property on the Picker instance to null .

So using your code example and preventing the re-firing of the OnSelectedIndexChanged event when assigning it null :

public void OptionSelect_OnSelectedIndexChanged(object sender, EventArgs e)
{
    var option = OptionSelect.SelectedItem;
    // Prevent setting the SelectedItem from refiring event
    OptionSelect.SelectedIndexChanged -= OptionSelect_OnSelectedIndexChanged;
    OptionSelect.SelectedItem = null;
    OptionSelect.SelectedIndexChanged += OptionSelect_OnSelectedIndexChanged;
    // Do something with option object
}

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