Xamarin / SQLite: обновление удваивается в базе данных - PullRequest
0 голосов
/ 29 января 2020

Я работаю над приложением Xamarin.Forms, которое будет хранить список рецептов для некоторых химических веществ. Химические вещества имеют названия (не изменяемые пользователем) и концентрации. Я хочу, чтобы пользователь мог изменять концентрации в форме и сохранять их.

У меня есть его, где я могу изменить значения в списке с помощью кнопки ОБНОВИТЬ, я могу добавлять (или удалять) членов список, все настойчиво. Тем не менее, я не могу понять, как изменить значения в списке внутри поля ввода, сам.

Я пытался сделать что-то вроде Arvind Chourasiya сделал здесь , но я не мог понять, из эквивалентного "connection.Update." Я думаю, что SQLite не может быть подключен, потому что он не в нужном событии, но я не уверен.

Мой самый функциональный код C# это ...

using System;
using System.ComponentModel;
using Xamarin.Forms;
using SQLite;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;

namespace contactBook
{

    public class Recipe : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        private string _name;

        [MaxLength(255)]
        public string Name
        { 
            get { return _name; }
            set
            {
                if (_name == value)
                    return;

                _name = value;

                OnPropertyChanged();
            }
        }

        private double _concentration;

        public double Concentration
        {
            get
            { return _concentration; }
            set
            {
                if (_concentration == value)
                    return;

                _concentration = value;

                OnPropertyChanged();
            }
        }

        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        private SQLiteAsyncConnection _connection;
        private ObservableCollection<Recipe> _recipes;

        public MainPage()
        {
            InitializeComponent();

            _connection = DependencyService.Get<ISQLiteDb>().GetConnection();
            //setBasicReceipies();

        }

        protected override async void OnAppearing()
        { 
            await _connection.CreateTableAsync<Recipe>();

            var recipes = await _connection.Table<Recipe>().ToListAsync();
            _recipes = new ObservableCollection<Recipe>(recipes);
            recipesListView.ItemsSource = _recipes;

            base.OnAppearing();
        }

        async void setBasicReceipies()  // worked during tests
        {

            var recipe1 = new Recipe { Name = "NH3", Concentration = 0.0 };
            var recipe2 = new Recipe { Name = "H2SO4", Concentration = 0.1 };
            var recipe3 = new Recipe { Name = "NaCl", Concentration = 0.2 };

            await _connection.InsertAsync(recipe1);
            await _connection.InsertAsync(recipe2);
            await _connection.InsertAsync(recipe3);
        }

        async void OnAdd(object sender, System.EventArgs e)
        {
            var recipe = new Recipe { Name = "test ", Concentration = 0.0 };
            await _connection.InsertAsync(recipe);

            _recipes.Add(recipe);
        }

        async void OnUpdate(object sender, System.EventArgs e)
        {
            var recipe = _recipes[0];
            recipe.Concentration += 0.05;

            await _connection.UpdateAsync(recipe);
        }

        async void OnDelete(object sender, System.EventArgs e)
        {
            var recipe = _recipes[0];
            await _connection.DeleteAsync(recipe);
            _recipes.Remove(recipe);
        }

        //async void Entry_PropertyChanged(System.Object sender, System.ComponentModel.PropertyChangedEventArgs e)
        //{
        //    await _connection.UpdateAllAsync();
        //}

    }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...