从帮助程序类事件侦听器回调到ContentPage

时间:2019-04-03 14:20:50

标签: forms firebase xamarin xamarin.forms callback

我有一个简单的Xamarin Forms项目,用于测试与Firebase实时数据库的交互。它包括一个主页,带有用于添加,编辑,删除和查询数据库的按钮。 Firebase帮助器类包含执行这些操作的所有代码,以及在添加,更新或删除数据时触发事件的可观察预订。 我需要由observable事件调用的“ ShowData”方法对ContentPage进行回调以刷新列表。

我不确定该如何完成。我以为可以在ContentPage中添加一个委托方法,但是不知道如何在页面中编写代码。

非常感谢您的帮助。

Firebase助手类

using System;
using System.Collections.Generic;
using XamarinFirebase.Model;
using Firebase.Database;
using Firebase.Database.Query;
using System.Linq;
using System.Threading.Tasks;
using Firebase.Database.Streaming;
using Xamarin.Forms;

namespace XamarinFirebase.Helper
{

    public class FirebaseHelper
    {
        FirebaseClient firebase = new FirebaseClient("https://xamarinfirebase-bdc74.firebaseio.com/");
        bool init = false;
        int status = 0;

        public void ShowData(FirebaseEvent<Person> e)
        {
            try
            {
                switch (e.EventType)
                {
                    case FirebaseEventType.Delete:
                        if (status == 4)
                        {
                            Device.BeginInvokeOnMainThread(async () =>
                            {
                                await Application.Current.MainPage.DisplayAlert("Deleted", e.EventSource.GetType().ToString() + " - " + e.Object.Name, "OK");
                            });
                        }
                        break;
                    case FirebaseEventType.InsertOrUpdate:
                        if (status == 2)
                        {
                            Device.BeginInvokeOnMainThread(async () =>
                            {
                                await Application.Current.MainPage.DisplayAlert("Added", e.EventSource.GetType().ToString() + " - " + e.Object.Name, "OK");
                            });
                        }
                        if (status == 3)
                        {
                            Device.BeginInvokeOnMainThread(async () =>
                            {
                                await Application.Current.MainPage.DisplayAlert("Updated", e.EventSource.GetType().ToString() + " - " + e.Object.Name, "OK");
                            });
                        }
                        break;
                    default:
                        Device.BeginInvokeOnMainThread(async () =>
                        {
                            await Application.Current.MainPage.DisplayAlert("Unknown", e.EventSource.GetType().ToString() + " - " + e.Object.Name, "OK");
                        });
                        break;
                }

                status = 0;
            }
            catch (Exception)
            {

                throw;
            }
        }

        public async Task<List<Person>> GetAllPersons()
        {
            if (!init)
            {
                var observable = firebase
                    .Child("Persons")
                    .AsObservable<Person>()
                    .Subscribe(d => ShowData(d));

                init = true;
            }

            status = 1;

            return (await firebase
              .Child("Persons")
              .OnceAsync<Person>()).Select(item => new Person
              {
                  Name = item.Object.Name,
                  PersonId = item.Object.PersonId
              }).ToList();
        }

        public async Task<Person> GetPerson(int personId)
        {
            status = 1;

            var allPersons = await GetAllPersons();
            await firebase
              .Child("Persons")
              .OnceAsync<Person>();
            return allPersons.Where(a => a.PersonId == personId).FirstOrDefault();
        }

        public async Task AddPerson(int personId,string name)
        {
            status = 2;

            await firebase
              .Child("Persons")
              .PostAsync(new Person() { PersonId=personId, Name = name });
        }

        public async Task UpdatePerson(int personId, string name)
        {
            status = 3;

            var toUpdatePerson = (await firebase
              .Child("Persons")
              .OnceAsync<Person>()).Where(a => a.Object.PersonId == personId).FirstOrDefault();

            await firebase
              .Child("Persons")
              .Child(toUpdatePerson.Key)
              .PutAsync(new Person() { PersonId = personId, Name = name });
        }

        public async Task DeletePerson(int personId)
        {
            status = 4;

            var toDeletePerson = (await firebase
              .Child("Persons")
              .OnceAsync<Person>()).Where(a => a.Object.PersonId == personId).FirstOrDefault();
            await firebase.Child("Persons").Child(toDeletePerson.Key).DeleteAsync();

        }
    }

}

ContentPage

using System;
using Xamarin.Forms;
using XamarinFirebase.Helper;

namespace XamarinFirebase
{
    public partial class MainPage : ContentPage
    {
        FirebaseHelper firebaseHelper = new FirebaseHelper();

        public MainPage()
        {
            InitializeComponent();
        }

        protected async override void OnAppearing()
        {

            base.OnAppearing();
            var allPersons = await firebaseHelper.GetAllPersons();
            lstPersons.ItemsSource = allPersons;
        }

        private async void BtnAdd_Clicked(object sender, EventArgs e)
        {
            try
            {
                await firebaseHelper.AddPerson(Convert.ToInt32(txtId.Text), txtName.Text);
                txtId.Text = string.Empty;
                txtName.Text = string.Empty;
                var allPersons = await firebaseHelper.GetAllPersons();
                lstPersons.ItemsSource = allPersons;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private async void BtnRetrive_Clicked(object sender, EventArgs e)
        {
            try
            {
                var person = await firebaseHelper.GetPerson(Convert.ToInt32(txtId.Text));
                if (person != null)
                {
                    txtId.Text = person.PersonId.ToString();
                    txtName.Text = person.Name;

                }
                else
                {
                    await DisplayAlert("Success", "No Person Available", "OK");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        private async void BtnUpdate_Clicked(object sender, EventArgs e)
        {
            try
            {
                await firebaseHelper.UpdatePerson(Convert.ToInt32(txtId.Text), txtName.Text);
                txtId.Text = string.Empty;
                txtName.Text = string.Empty;
                var allPersons = await firebaseHelper.GetAllPersons();
                lstPersons.ItemsSource = allPersons;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private async void BtnDelete_Clicked(object sender, EventArgs e)
        {
            try
            {
                await firebaseHelper.DeletePerson(Convert.ToInt32(txtId.Text));
                var allPersons = await firebaseHelper.GetAllPersons();
                lstPersons.ItemsSource = allPersons;
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

Xamarin表单消息中心可以为您完成

在contentPage中订阅消息:

MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => {
// Your code here
});

然后在内容页面上显示一条消息,例如:

MessagingCenter.Send<MainPage> (this, "Hi"); 

字符串不变-它指示消息类型,用于确定要通知的订户。这种消息用于指示发生了某些事件,例如“上传完成”,不需要进一步的信息。

在两种情况下,

注意 this是MainPage实例。

为了更好地理解,请检查Messaging Center