我在读this在消息中心发帖。当我在我的数据存储类中遇到错误时,我想使用这种方法来显示错误(如果这不是 kosher,请告诉我)。但是,它不起作用。
登录页面.xaml.cs
public partial class LoginPage : ContentPage
{
public LoginPage()
{
InitializeComponent();
MessagingCenter.Subscribe<LoginDataStore, MessagingCenterAlert>(this, "message", (sender, arg) =>
{
Device.BeginInvokeOnMainThread(() =>
{
DisplayAlert("UH OH!", arg.Message, "OK");
});
});
}
}
登录数据存储.cs
public class LoginDataStore
{
HttpClient client;
public LoginDataStore()
{
client = new HttpClient();
client.BaseAddress = new Uri($"{App.BackendUrl}/");
}
public async void Login(string username, string password)
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("email", username),
new KeyValuePair<string, string>("password", password)
});
try
{
var result = await client.PostAsync("/oauth/token", content);
string resultContent = await result.Content.ReadAsStringAsync();
if (!result.IsSuccessStatusCode)
throw new Exception(result.StatusCode.ToString() + System.Environment.NewLine + "Please check your email and password.");
dynamic resultObject = JsonConvert.DeserializeObject(resultContent);
Settings.AuthToken = (string)resultObject["access_token"].Value;
Settings.UserId = username;
}
catch (Exception e)
{
// remove later when the messaging center works
await Application.Current.MainPage.DisplayAlert("Login Failed!", e.Message, "OK");
MessagingCenter.Send(new MessagingCenterAlert
{
Title = "Login Failed",
Message = e.Message,
Cancel = "OK"
}, e.Message);
return;
}
}
}
当我运行带有断点的代码时,我可以看到正在创建消息并且订阅了登录页面,但是订阅中的代码永远不会被调用并且没有消息出现。直接调用页面的蛮力代码可以工作,但并不十分优雅。
最佳答案
你的订阅者没有监听发送者发送的相同的message
键。他们需要像这样匹配:
MessagingCenter.Subscribe<LoginDataStore, MessagingCenterAlert> (this, "LoginFailureMessage", (sender, args) => {
// do something whenever the "LoginFailureMessage" message is sent
});
MessagingCenter.Send<LoginDataStore, MessagingCenterAlert> (this, "LoginFailureMessage", new MessagingCenterAlert
{
Title = "Login Failed",
Message = e.Message,
Cancel = "OK"
});
关于c# - Xamarin Forms 错误处理 - 消息中心警报未从数据存储中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47687012/