如何将piker的价值保存到Realm db?

时间:2016-09-20 15:25:44

标签: xamarin.forms realm picker

我正在与Realm合作,我的例子与@BenBishop的this类似。我在PersonPage中添加了Yes / No选择器,并尝试将选择器的选定值保存到我的数据库中。请问有人帮我吗?谢谢!

1 个答案:

答案 0 :(得分:0)

这不是真正的Realm问题,因为该示例仅在内部使用Realm进行存储。它的大部分代码都是通用的C#Xamarin代码。

作为快速摘要,您需要

  1. AddEditPersonViewModel.cs
  2. 中添加媒体资源
  3. 更新AddEditPersonViewModel.Init以加载新属性
  4. PersonPage.xaml
  5. 中添加映射到该属性的选择器
  6. Person.cs中添加匹配的属性以存储该值
  7. 更新IDBService.SavePerson以允许传递新属性
  8. 更新RealmDBService.SavePerson以将新属性复制回Realm
  9. 详细说明:

    // step 1 & 2
    public class AddEditPersonViewModel : INotifyPropertyChanged
    {
    ...
    // added property
        private int superPower;
    
        public int SuperPower {
            get {
                return superPower;
            }
            set {
                superPower = value;
                PropertyChanged(this, new PropertyChangedEventArgs("SuperPower"));
            }
        }
    ...
        public void Init (string id)
        {
        ...
            SuperPower = Model.SuperPower;
    
    
    
    // step 3 - in PersonPage.xaml
            Text="{Binding LastName}" />
          <Picker SelectedIndex="{Binding SuperPower}">
            <Picker.Items>
              <x:String>Flight</x:String>
              <x:String>Super Strength</x:String>
              <x:String>Ordinariness</x:String>
            </Picker.Items>
          </Picker>
        </StackLayout>
    
    
    // step 4 - in Person.cs
      public class Person : RealmObject
      {
      ...
          public int SuperPower { 
              get; 
              set;
          }
    
    
    // step 5 in IDBService.cs
        public interface IDBService
        {
            bool SavePerson (string id, string firstName, string lastName, int SuperPower);
    
    
    // step 6 in RealmDBService.cs
      public class RealmDBService : IDBService
      {
      ...
          public bool SavePerson (string id, string firstName, string lastName, int superPower)
        {
            try {
                RealmInstance.Write (() => {
                    var person = RealmInstance.CreateObject<Person> ();
                    person.ID = id;
                    person.FirstName = firstName;
                    person.LastName = lastName;
                    person.SuperPower = superPower;
                });