18
votes

Can i Trigger a Picker programatically?

I would like a button beside the picker that indicates that the picker is a clickable "dropdown". But how could I open the picker when the button is clicked?

3
BTW, if Picker class isn't providing what you want, a more flexible approach is seen in "Action Sheet" sample in Allan Ritchie - "ACR.UserDialogs" nuget src. Defined via a descriptive config object in StandardViewModel.CreateActionSheetCommand. On UWP, this is based on UWP XAML ContentDialog class. On iOS and Android, appropriate native controls are built.ToolmakerSteve
... I'm not sure why that nuget doesn't instead build on Xamarin Forms ContentView class - doing so would make it easier to generate custom cross-platform dialogs. I mention the UWP implementation above, because it looks like something that could be adapted to use X-Forms views w/i a contentview. See UserDialogsImpl under Platforms / UWP.ToolmakerSteve

3 Answers

14
votes

You can name the picker (e.g. myPicker) and call its Focus event. Do make sure that you're on the main thread at the time you're calling myPicker.Focus()

9
votes

As @Hutjepower and this xamarin forums post mentions, the following code should work:

Device.BeginInvokeOnMainThread(() =>
{
    if (yourPicker.IsFocused)
        yourPicker.Unfocus();

    yourPicker.Focus();
});

However I have found that it does not currently work on Windows 8.1 and UWP apps, at least in the latest 2.3.4-pre1 version of Xamarin.Forms. I haven't tested it on any phone/tablet devices yet though. Hopefully this bug will get fixed up in a later release. I have created a bug report for this problem.

1
votes

Unfortunately not; the inner workings of the picker are almost entirely in the renderers and are not exposed via an API.