C# 从SQLite-Xamarin.Forms保存和读取选择器值
我想让你帮我解决一个我无法解决的问题 在我的Xamarin.Forms应用程序中,用户可以向SQLite数据库添加:C# 从SQLite-Xamarin.Forms保存和读取选择器值,c#,sqlite,xaml,xamarin.forms,C#,Sqlite,Xaml,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; } } Pic
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>
值1
价值2
在另一个页面上,使用ListView显示项目:
<Label Text="{Binding Text}"/>
<Label Text="{Binding PickerValue}"/>
当我在ListView上选择一个项目时,编辑页面将为我打开,这是我添加新产品(上面的代码)的同一页面,其中包含来自数据库的填充字段。我可以在那里编辑它们
我希望能够将所选选择器值保存到SQLite,并在另一个页面上显示它(或所选值的索引)。有人能帮我做这样的装订吗
如果可能的话,我想用XAML来做
我根据以下内容制作了这个项目:这是我的GIF 您可以直接设置此选择器 首先,我在模型中添加了一个属性,这里是添加一个性别属性
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; }
}
在将数据插入数据库之前,应该像下面的代码一样设置此属性代码>至字符串
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();
}
在另一个页面中,我们只绑定性别属性,如下面的代码
<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>
这是我的演示
更新
有关于更改编辑页面文本的GIF,工作正常。
我只是添加picker的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>
女的
男性的
我再次更新我的项目。
非常感谢您的回复。它工作得很好。不幸的是,我有一个问题。将PickerValue插入SQLite可以正常工作,在ListView上显示插入的项目也可以工作。但是,当我单击ListView上的项目并转到EditPage(与我添加新项目时相同)-每次更改并重新保存(49/5000,即使我不更改任何内容并单击保存)->“未处理的异常:System.Reflection.TargetInvocationException:调用的目标已引发异常。“。你知道原因是什么吗?@erbeen这个问题发生在你的项目还是我的项目中?如果它发生在我的项目中,我必须更新我的anwer,检查此函数,它工作正常,您还可以在调试之前更改此数据库的另一个名称。如果此问题发生在您的项目中,您没有发布相关代码,我不知道哪行会导致此问题,请标记此线程(因为此线程与保存和读取SQLite中的选择器值相关,已解决),然后打开一个新线程,发布相关代码,然后我们就可以解决这个新问题了。从这里可以吗?
async void OnSelectionChanged(object sender,SelectionChangedEventArgs e){if(e.CurrentSelection!=null){//导航到NoteEntryPage,将ID作为查询参数传递。Note Note Note=(Note)e.CurrentSelection.FirstOrDefault();wait Shell.Current.GoToAsync($“{nameof(notentrypage)}?{nameof(notentrypage.ItemId)}={note.ID.ToString()}”);}