Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xamarin picker control selectedindexchange event raised only when done picking item

I am using an Xamarin.Forms.Picker control and handling the SelectedIndexChanged event.

The user scrolls thru the items in the picker control then the user selects the "Done" button that is prebuilt into the picker control. Is there anyway to capture when the user presses "Done" instead of when the index changes.

The index can change multiple times as the user scrolls thru the items and I don't want to handle unnecessary events as I only care about the last item selected.

Thanks in advance

<Picker x:Name="PickerMinStars" Title="Min number of 5 stars"  SelectedIndexChanged="Handle_PickerStarsSelectedIndexChanged">
        </Picker>
like image 813
Jason Smith Avatar asked Dec 28 '17 01:12

Jason Smith


3 Answers

To handle the selection change event from XAML code, as Pieter Nijs has suggested in his blog

<Picker ItemsSource="{Binding FooList}"
    SelectedItem="{Binding SelectedFoo}"
    ItemDisplayBinding="{Binding Name}"
    iOSSpecific:Picker.UpdateMode="WhenFinished" />

This requires to add reference of

xmlns:iOSSpecific="clr-namespace:Xamarin.Forms.PlatformConfiguration.iOSSpecific;assembly=Xamarin.Forms.Core"

Which will raise selected index changed event after tapping ok.

like image 39
Mukesh Modhvadiya Avatar answered Sep 27 '22 22:09

Mukesh Modhvadiya


You can bind the SelectedItem to a property in your ViewModel. The property will only update when the data is changed.

<Picker SelectedItem="{Binding SelectedItemProperty}" />
like image 27
lowleetak Avatar answered Sep 27 '22 22:09

lowleetak


There are three workarounds to achieve your requirement.

Simple

set unfoucus event on Picker , it triggers when the picker are going to dismiss (click on the Done button or the outside area of the picker).

Medium

delay the SelectedIndexChanged event firing until after you tap Done button.

picker.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished);

Complex

create Custom Renderers to handle Done button click event.

public class MyPickerRenderer : PickerRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
    {
        base.OnElementChanged(e);

        if(e.OldElement != null)
        {
            var toolbar = (UIToolbar)Control.InputAccessoryView;
            var doneBtn = toolbar.Items[1];

            doneBtn.Clicked -= DoneBtn_Clicked;
        }

        if(e.NewElement != null)
        {
            var toolbar = (UIToolbar)Control.InputAccessoryView;
            var doneBtn = toolbar.Items[1];

            doneBtn.Clicked += DoneBtn_Clicked;
        }
    }

    void DoneBtn_Clicked(object sender, EventArgs e)
    {
        Console.WriteLine("Clicked!!!!");
    }
}

Refer to

How can we handle the done button click event for a Xamarin Forms Picker?

Picker Selection Event

like image 102
ColeX - MSFT Avatar answered Sep 27 '22 23:09

ColeX - MSFT