首页 > 解决方案 > 从 SQLite 保存和读取 Picker 值 - 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

标签: c#sqlitexamlxamarin.forms

解决方案


这是我的跑步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;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


推荐阅读