Home > Blockchain >  How to make a simple number picker in Xamarin Forms and store selected value in a variable
How to make a simple number picker in Xamarin Forms and store selected value in a variable

Time:12-17

I'm mostly new to coding - and I've been stuck on something which probably is very basic:

I'm trying to make a simple picker/drop down menu with numbers ranging from 1-30. And then: I'd like to store the selected number in a variable for use on several other C# pages of the app.

Does anyone know how to do this?

Thanks!

I've gone through a lot of tutorials - but most end up with bugs when I try to adjust the code. Also for many I'm not sure what to adjust.

CodePudding user response:

It's easy to achieve using MVVM pattern. For more information, you could refer to Xamarin.Forms Picker, Xamarin.Forms Data Binding and Part 5. From Data Bindings to MVVM.

I made a small demo for you.

In xaml file, define a Picker. Use the ItemsSource and SelectedItem property. Also we add a new button, the Command property of which is binded to SelectedCommand in the viewmodel.

<Picker x:Name="mypicker"
    ItemsSource="{Binding ItemCollection}"    
    SelectedItem="{Binding SelectedItem}"  />
<Button x:Name="mybutton"  Command="{Binding SelectedCommand}" BackgroundColor="Yellow" Text="button1" />

In MainPage.xaml.cs file, set the BindingContext:

this.BindingContext = new MainPageViewModel(); 

In MainPageViewModel.cs file:

public class MainPageViewModel
{
    int participantsturn = 1;
    public int SelectedItem { get; set; } // you can access the picker value through this property
    public ObservableCollection<int> ItemCollection { get; set; }

    public MainPageViewModel()
    {
        ItemCollection = new ObservableCollection<int>();
        CreateCollection();  //generate ItemSource for the picker
    }

    public Command SelectedCommand
    {
        get
        {
            return new Command(() =>
            {
                if (participantsturn == SelectedItem)
                {
                    Console.WriteLine("yes!!!!!!!!!!!");
                }else
                {
                    Console.WriteLine("no!!!!!!!!!!!!");
                }                 
            });
        }
    }
    private void CreateCollection()
    {
        var numList = Enumerable.Range(1, 30).ToList();
        ItemCollection = new ObservableCollection<int>(numList);
    }
}

Hope it works for you. If you still have any question, feel free to ask.

  • Related