c# - 从 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
解决方案
这是我的跑步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
我只是添加了选择器的 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
推荐阅读
- php - 正确使用 in_array()
- python - 为什么 Biterm 主题模型 (BTM) 返回连贯性分数 -100?
- typescript - 打字稿按顺序排列多个承诺
- r - 为什么使用 Lapply 出现服务不可用错误?
- animation - 创建具有透明背景的 SVG 动画虚线
- c++ - new 可以给出除 bad_alloc 以外的异常
- python - 如何使用python从csv到xml的单个单元格中提取多个值
- scala - 使用值序列火花从 RDD 中过滤数据
- java - Ksoap2 库到 android studio 错误消息,如何修复?
- xml - xslt 从嵌套循环中选择匹配值