有什么办法可以订阅&吗?使用mvvm light Xamarin Forms发送通用类型类的消息传递中心 [英] Is there any way to subscribe & send messaging center for generic type class using mvvm light Xamarin Forms
问题描述
这就是我现在正在做的事情,有没有更好的解决方案可以使这种通用
That's how i am doing it right now, is there any better solution for making this generic
MessagingCenter.Send(this, "XYZ", "XYZ" + " Recieved");
MessagingCenter.Subscribe<MyService, string>(this, "XYZ", async (sender, arg) =>
{
//TO-DO
});
推荐答案
我们如何使用Xamarin形式的消息传递中心发送消息: 这是我在下面的方法中使用的行:-
How we use to send message using messaging center in xamarin forms:- This is the line I have used In bellow method:-
MessagingCenter.Send(this, typeof(T).Name, typeof(T).Name + " Recieved");
DatabaseService.cs ---我从"DatabaseService.cs"发送此消息,因此将其写在第一个参数中的第二个参数typeof(T)中以供参考.其中"T"是通用类.(T是Azure下载完成后的表名我正在发送消息以标识数据是从Azure服务器到达的,并保存在本地数据库中),波纹管方法中的第二个参数也是typeof(T). "Receieved"和"Receieved"是我要传递的参数,用于标识是从存储中接收数据还是从存储中删除数据,以标识我对SQLite DB进行了哪种操作.
DatabaseService.cs --- I am sending this message from "DatabaseService.cs" so writting this for reference in first paramenter, in second parameter typeof(T).Name where "T" is generic class.(T is Azure Table name after downloading done I am sending message to identify the data is arrived from Azure server and saved in Local DB) , second paramenter in the bellow method is also typeof(T).Name which referes to key for which sender and receiver are subscribed and "Receieved" is arguments that I am passing to Identify that the data is received or deleted from store to identify which sort of operation I have performed on SQLite DB.
/// <summary>
/// Function to retrive Records from Azure Server and insert/Update those into localDB .
/// </summary>
/// <typeparam name="T">Table Name</typeparam>
/// <param name="data">Records retrived from Azure Server that are being insrted to localDB.</param>
/// <returns></returns>
public async Task InsertDataToLocalDB<T>(List<T> data)
{
List<JObject> jDatas = new List<JObject>();
for (int index = 0; index < data.Count; index++)
{
jDatas.Add(JObject.FromObject(data[index]));
}
try
{
await _store.UpsertAsync(typeof(T).Name, jDatas, true); //_Store is MobileServiceSQLiteStore SQLite store
}
catch (Exception ww)
{
//throw;
}
MessagingCenter.Send(this, typeof(T).Name, typeof(T).Name + " Recieved");
}
我们如何订阅消息:-
MessagingCenter.Subscribe<DatabaseService, string>(this, "Notification", async (sender, arg) =>
{
//After Receiving Notifications from server Call Refresh Command
await RefreshCommand.ExecuteAsync();
});
这篇关于有什么办法可以订阅&吗?使用mvvm light Xamarin Forms发送通用类型类的消息传递中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!