繁体   English   中英

从SQLite保存和读取Picker值-Xamarin.Forms

[英]Saving and reading Picker values from SQLite - Xamarin.Forms

我希望您能帮助我解决我无法解决的问题。

在我的Xamarin.Forms应用程序中,用户可以添加到SQLite数据库:

public class Car
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Text { get; set; }
        public int PickerValue { get; set; }
    }

PickerValue的类型为INT,因为我认为选择器的选定值给出了索引INT值。 我错了吗?

用户使用以下项添加项目:

<Editor Placeholder="Enter name" Text="{Binding Text}" />
<Picker x:Name="myPicker" Title="Value:">
            <Picker.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>value 1</x:String>
                    <x:String>value 2</x:String>
                </x:Array>
            </Picker.ItemsSource>
        </Picker>

在另一页上,使用ListView显示项目:

<Label Text="{Binding Text}"/>
<Label Text="{Binding PickerValue}"/>

当我在ListView上选择一个项目时-编辑页面将为我打开-在同一页面中我添加了具有数据库中填充字段的新产品(上面的代码)。 我可以在那里编辑它们。

我希望能够将选定的Picker值保存到SQLite,然后在另一页上可以显示它(或选定值的索引)。 有人可以帮我怎么做这样的绑定吗?

如果可能的话-我想在XAML中做到这一点。

我基于以下项目创建了项目: https : //docs.microsoft.com/pl-pl/xamarin/get-started/quickstarts/database?pivots=windows

这是我正在运行的GIF。

在此处输入图片说明 您可以直接设置此选择器。

首先,我在模型中添加一个属性,这里添加了Gender属性。

   public class Note
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Text { get; set; }
    public DateTime Date { get; set; }

    public  string Gender { get; set; }
}

在将数据插入数据库之前,应像下面的myPicker.SelectedItem;一样设置此属性。应转换myPicker.SelectedItem; string

 async void OnSaveButtonClicked(object sender, EventArgs e)
    {
        var note = (Note)BindingContext;
        note.Date = DateTime.UtcNow;
        note.Gender = (string)myPicker.SelectedItem;
        await App.Database.SaveNoteAsync(note);
        await Navigation.PopAsync();
    }

在另一页中,我们仅绑定Gender属性,如以下代码所示。

  <ListView x:Name="listView"
          Margin="20"
          ItemSelected="OnListViewItemSelected">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
             <StackLayout>
                <Label Text="{Binding Text}"></Label>

                <Label Text="{Binding Gender}"></Label>
            </StackLayout>

            </ViewCell>
          </DataTemplate>
    </ListView.ItemTemplate>

这是我的演示。

https://github.com/851265601/databaseDemo

更新有关于更改编辑页面文本的GIF,它可以正常工作。 在此处输入图片说明

我只是添加选择器的SelectedItem,

   <Picker x:Name="myPicker" Title="Value:" SelectedItem="{Binding Gender}">
        <Picker.ItemsSource>
            <x:Array Type="{x:Type x:String}">
                <x:String>female</x:String>
                <x:String>male</x:String>
            </x:Array>
        </Picker.ItemsSource>
    </Picker>

我为我的项目再次更新。 https://github.com/851265601/Datademo3/blob/master/Datademo2/Notes/App.xaml.cs

暂无
暂无

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

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