来自Xamarin.Android项目的Xamarin.Forms调用对话框引发异常
我一直在尝试使用IoC容器从我的xamarin.forms应用程序调用对话框警报,到目前为止,我无法使用以下代码在我的应用程序中显示警报: 我的viewModel中的代码:来自Xamarin.Android项目的Xamarin.Forms调用对话框引发异常,xamarin,xamarin.forms,xamarin.android,dialog,android-alertdialog,Xamarin,Xamarin.forms,Xamarin.android,Dialog,Android Alertdialog,我一直在尝试使用IoC容器从我的xamarin.forms应用程序调用对话框警报,到目前为止,我无法使用以下代码在我的应用程序中显示警报: 我的viewModel中的代码: await _dialogService.DisplayMessageAsync("ERROR", "There are errors on your form!", "Cancel", null); public class DialogService : IDialogService { readonly ID
await _dialogService.DisplayMessageAsync("ERROR", "There are errors on your form!", "Cancel", null);
public class DialogService : IDialogService
{
readonly IDialogService _dialogService;
public DialogService()
{
_dialogService = DependencyService.Get<IDialogService>();
}
public void CloseAllDialogs()
{
_dialogService.CloseAllDialogs();
}
public async Task DisplayMessageAsync(string title, string message, string buttonCancelName, Action callback)
{
await _dialogService.DisplayMessageAsync(title, message, buttonCancelName, callback);
}
public async Task DisplayMessageConfirmAsync(string title, string message, string buttonOkName, string buttonCancelName, Action<bool> callback)
{
await _dialogService.DisplayMessageConfirmAsync(title, message, buttonOkName, buttonCancelName, callback);
}
}
在我的共享项目中,我有一个DialogService,我从viewModel调用它:
await _dialogService.DisplayMessageAsync("ERROR", "There are errors on your form!", "Cancel", null);
public class DialogService : IDialogService
{
readonly IDialogService _dialogService;
public DialogService()
{
_dialogService = DependencyService.Get<IDialogService>();
}
public void CloseAllDialogs()
{
_dialogService.CloseAllDialogs();
}
public async Task DisplayMessageAsync(string title, string message, string buttonCancelName, Action callback)
{
await _dialogService.DisplayMessageAsync(title, message, buttonCancelName, callback);
}
public async Task DisplayMessageConfirmAsync(string title, string message, string buttonOkName, string buttonCancelName, Action<bool> callback)
{
await _dialogService.DisplayMessageConfirmAsync(title, message, buttonOkName, buttonCancelName, callback);
}
}
对于这一行代码:
var alert = new AlertDialog.Builder(Android.App.Application.Context);
var activity = (Activity)Forms.Context;
var alert = new AlertDialog.Builder(activity);
使用它的问题是我得到一个Xamarin.Forms警告,如下所示:
“Forms.Context”已过时:“Context从2.5版起已过时。
请改用本地上下文。”
我有点固执,我不喜欢有警告,并尽量保持我的代码更新,所以,有人可以帮助我使这个代码工作,而不需要使用过时的代码。因为我找到的答案是,只需将ActivityForms.Context替换为Android.App.Application.Context就可以了,但在这种情况下根本不起作用
希望有人能给我指出正确的方向,因为我还没有找到任何关于这个案例的文档。问题是Android.App.Application.Context并不总是活动上下文
Xamarin删除了这一点,并为包含上下文的渲染器添加了一个新的构造函数。问题出现在这样的情况下,即您正在处理的不是CustomRenderer的东西
对于这些情况,我使用James的插件CurrentActivityPlugin,它将为您跟踪当前活动。找到它
希望这有帮助-