gpt4 book ai didi

xamarin - 如何在 Xamarin 中从 ViewModel 创建警报弹出窗口?

转载 作者:行者123 更新时间:2023-12-02 10:48:18 27 4
gpt4 key购买 nike

我正在使用 MVVM 模式开发 Xamarin 应用程序。我想在用户按下按钮时向用户显示警报。

我用

声明我的 ViewModel
class MainPageViewModel : BindableBase   {

不幸的是,我无法直接从 ViewModel 中访问 Page 对象。我如何最好地显示我的警报?

最佳答案

虽然迟到了,但正如 Nick Turner 在许多评论中提到的那样,到目前为止给出的解决方案要求 View 模型引用 View ,这是 MVVM 的反模式/侵权。此外,您还会在 View 模型单元测试中遇到错误,例如:您必须调用 Xamarin.Forms.Init();在使用它之前。

相反,您可以创建一个包含警报框代码的界面,然后在 View 模型中使用,如下所示:

界面:

public interface IDialogService
{
Task ShowAlertAsync(string message, string title, string buttonLabel);
}

实现(使用 ACR.UserDialogs NuGet 包):

public class DialogService : IDialogService
{
public async Task ShowAlertAsync(string message, string title, string buttonLabel)
{
if (App.IsActive)
await UserDialogs.Instance.AlertAsync(message, title, buttonLabel);
else
{
MessagingCenter.Instance.Subscribe<object>(this, MessageKeys.AppIsActive, async (obj) =>
{
await UserDialogs.Instance.AlertAsync(message, title, buttonLabel);
MessagingCenter.Instance.Unsubscribe<object>(this, MessageKeys.AppIsActive);
});
}
}
}

View 模型:

public class TestViewModel
{
private readonly IDialogService _dialogService;

public TestViewModel(IDialogService dialogService)
{
//IoC handles _dialogService implementation
_dialogService = dialogService ?? throw new ArgumentNullException(nameof(dialogService));
}

public ICommand TestCommand => new Command(async () => await TestAsync());

private async Task TestAsync()
{
await _dialogService.ShowAlertAsync("The message alert will show", "The title of the alert", "The label of the button");
}
}

然后可以将 TestCommand 绑定(bind)到 xaml 中的按钮:

<Button x:Name="testButton" Command="{Binding TestCommand}">

关于xamarin - 如何在 Xamarin 中从 ViewModel 创建警报弹出窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52984946/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com