繁体   English   中英

如何在 Xamarin Forms 中制作一个简单的数字选择器并将选定的值存储在变量中

[英]How to make a simple number picker in Xamarin Forms and store selected value in a variable

我大多是编码新手 - 我一直坚持一些可能非常基本的东西:

我正在尝试制作一个简单的选择器/下拉菜单,其中的数字范围为 1-30。 然后:我想将选定的数字存储在一个变量中,以便在应用程序的其他几个 C# 页面上使用。

有谁知道如何做到这一点?

谢谢!

我已经阅读了很多教程 - 但当我尝试调整代码时,大多数教程都以错误告终。 对于许多人来说,我也不确定要调整什么。

使用 MVVM 模式很容易实现。 有关更多信息,您可以参考Xamarin.Forms PickerXamarin.Forms 数据绑定第 5 部分。从数据绑定到 MVVM

我为你做了一个小演示。

在 xaml 文件中,定义一个 Picker。 使用ItemsSourceSelectedItem属性。 我们还添加了一个新按钮,其 Command 属性绑定到视图模型中的 SelectedCommand。

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

在 MainPage.xaml.cs 文件中,设置 BindingContext:

this.BindingContext = new MainPageViewModel(); 

在 MainPageViewModel.cs 文件中:

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);
    }
}

希望对你有效。 如果您还有任何问题,请随时提问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM