如何使用Xamarin.Forms显示警报框进行验证?

时间:2014-12-17 06:42:14

标签: android ios iphone xamarin xamarin.forms

如何显示带Xamarin.Forms的警告框进行验证?

我知道我们可以使用以下来自ContentView代码的代码显示提醒但我想从我的ViewModel显示警告框。

DisplayAlert ("Alert", "You have been alerted", "OK");

我已使用以下代码注册了 ViewModel for View

ViewFactory.Register<[ContentPage], [ContentPageViewModel]> (); 

5 个答案:

答案 0 :(得分:41)

您可以通过静态Xamarin.Forms的{​​{1}}属性在MainPage项目的任何位置显示提醒,例如

App.Current

答案 1 :(得分:1)

您可以使用:

Application.Current.MainPage.DisplayAlert(title, message, buttonText)

但是,在视图模型中使用它是一种不好的做法。

相反,我认为,最佳实践是将其与视图模型和页面分离。 解决方案是创建一个服务,负责在您的应用程序中显示警报。您可以在下面找到问题的简单答案。但是,DisplayAlert方法有很多重载,您可以在服务中添加使用重载的新方法。

在一个代码中有两个简单的示例:

首先为您的服务实现接口:

public interface IDialogService
{
    public Task ShowErrorAsync(string message, string title, string buttonText);
    public Task ShowErrorAsync(string message, string title, string buttonText, Action CallBackAferHide);
}

然后,在具体实现中实现该接口:

public class DialogService : IDialogService
{
    public async Task ShowErrorAsync(string message, string title, string buttonText)
    {
        await Application.Current.MainPage.DisplayAlert(title, message, buttonText);
    }

    public async Task ShowErrorAsync(string message, string title, string buttonText, Action CallBackAferHide)
    {
        await Application.Current.MainPage.DisplayAlert(title, message, buttonText);
        CallBackAferHide?.Invoke();
    }
}

第一种方法允许您显示警报,第二种方法允许您提供一种回调方法,该方法将在用户关闭警报框后被调用-例如,导航回到上一页。

在两种情况下都可以使用第二种方法,只需调用:

await ShowErrorAsync("message", "title", "OK", null);

CallBackAferHide?.Invoke();首先检查是否提供了Action,然后如果它不为null,则调用。

在您的视图模型中,注入服务并仅调用提供参数的方法。

我希望这会有所帮助:)。 祝一切顺利!

答案 2 :(得分:0)

答案 3 :(得分:0)

@ Nirav-Mehta

请尝试使用以下代码在ViewModel中显示警报:

常规警报框:

App.Current.MainPage.DisplayAlert("Alert","You can write message here!!!","Ok");
OR
Application.Current.MainPage.DisplayAlert("Alert","You can write message here!!!","Ok");

问一个简单的问题警报框:

var answer = App.Current.MainPage.DisplayAlert("Question?", "Your Question Write Here !!!", "Yes", "No"));
OR
var answer = Application.Current.MainPage.DisplayAlert("Question?", "Your Question Write Here !!!", "Yes", "No"));
Debug.WriteLine("Answer: " + answer);

显示简单警报ActionSheet:

var action = App.Current.MainPage.DisplayActionSheet("ActionSheet: Send to?", "Cancel", null, "Email", "Twitter", "Facebook");
OR
var action = Application.Current.MainPage.DisplayActionSheet("ActionSheet: Send to?", "Cancel", null, "Email", "Twitter", "Facebook");
Debug.WriteLine("Action: " + action);

我希望上面的代码对您有用。

谢谢。

答案 4 :(得分:0)

使用Rg.Plugins.Popup Nuget

https://www.nuget.org/packages/Rg.Plugins.Popup/

这样定义弹出窗口:

>

<popup:PopupPage xmlns="http://xamarin.com/schemas/2014/forms" 
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:popup="clr-namespace:Rg.Plugins.Popup.Pages;assembly=Rg.Plugins.Popup"...

在ViewModel中(使用棱镜):

>

await NavigationService.NavigateAsync("NavigationPage/[View]");