Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to fire a click event on the Done button on a Picker in Xamarin Forms. I found some people having custom render for entry, but how can we implement the done button in a Picker on Xamarin forms iOS?

like image 723
shamnad Avatar asked Feb 06 '23 00:02

shamnad


1 Answers

You can use a custom renderer to achieve this. Looking at the source code for the Picker on iOS, you can see that the 'Done' button is added to a UIToolbar. You can get a reference to the button and then handle its 'Clicked' 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!!!!");
    }
}
like image 185
jimmgarr Avatar answered May 05 '23 04:05

jimmgarr