Search code examples
c#xamarinxamarin.formspicker

How to dynamically add a picker


I have a button on my screen and when I press the button I want a picker to show up with a list of items and when an item is chosen the text of the button should change to that and the picker should go away.

This is my code:

Picker picker = new Picker
    {
        Title = "What's in the slot?",
        VerticalOptions = LayoutOptions.CenterAndExpand
        //HorizontalOptions = LayoutOptions.Center 

    };

And the function which is called when the button is pressed:

private void Displaypickerview(int row, int column)
    {
        if (status == "filling board")
        {
            foreach (string text in pickerText)
            {
                picker.Items.Add(text);
            }
            foreach (string ore in oreLevels)
            {
                picker.Items.Add(ore);
            }


            picker.SelectedIndexChanged += (sender, args) =>
            {
                if (picker.SelectedIndex == -1)
                {

                }
                else
                {
                    //change value of cell and button
                    Picker picker = (Picker)sender;
                    int index = picker.SelectedIndex;

                    if (index < pickerText.Length)
                    {
                        board[row, column].Text = pickerText[index - 1];
                    }
                    else {
                        board[row, column].Text = oreLevels[index - 1 - pickerText.Length];
                    }
                }
            };
        }
        else if (status == "choosing item")
        {

        }

    }

But I don't know how i should render the picker view on the screen and remove it afterwards.

Update:

What is the eventhandler of the done button in the picture below.

Picker


Solution

  • You could add the picker to your Grid or whatever Panel you are using by adding it to the Children collection:

    Grid.SetRow(picker, 0); //first row
    Grid.SetColumn(picker, 0); //first column
    grid.Children.Add(picker);
    

    Similarly you remove it by removing it from the Children collection:

    grid.Children.Remove(picker);