就像@Alessandro 说的Application.Current.MainPage
也适用于操作表和警报。为了从视图模型中隐藏视图特定的内容,我创建了一个IMessageBoxService
它被注入到需要它的视图模型承包商中。请注意,我正在使用Autofac IoC 容器 http://autofac.readthedocs.io/en/latest/index.html。对于 Xamarin 的 DependencyService,您已更改构造函数并在代码中查找服务。
IMessageBoxService.cs
public interface IMessageBoxService
{
void ShowAlert(string title, string message, Action onClosed = null);
// ...
Task<string> ShowActionSheet(string title, string cancel, string destruction, string[] buttons = null);
}
MessageBoxService.cs
public class MessageBoxService : IMessageBoxService
{
private static Page CurrentMainPage { get { return Application.Current.MainPage; } }
public async void ShowAlert(string title, string message, Action onClosed = null)
{
await CurrentMainPage.DisplayAlert(title, message, TextResources.ButtonOK);
onClosed?.Invoke();
}
public async Task<string> ShowActionSheet(string title, string cancel, string destruction = null, string[] buttons = null)
{
var displayButtons = buttons ?? new string[] { };
var action = await CurrentMainPage.DisplayActionSheet(title, cancel, destruction, displayButtons);
return action;
}
}
应用程序安装程序.cs
protected void RegisterDependencies(ContainerBuilder cb)
{
// ...
cb.RegisterType<MessageBoxService>().As<IMessageBoxService>().SingleInstance();
}
Usage
public class EditProductViewModel : AddProductViewModel
{
private IMessageBoxService _messageBoxService;
public ICommand DeleteCommand { get; set; }
public EditProductViewModel(IPageNavigator navigator, IMessenger messenger,
IMessageBoxService messageBoxService, TagDataStore tagDataStore) : base(navigator, messenger, tagDataStore)
{
_messageBoxService = messageBoxService;
DeleteCommand = new Command(DeleteItem);
}
...
private async void DeleteItem()
{
var action = await _messageBoxService.ShowActionSheet(TextResources.MenuTitleDeleteProduct,
TextResources.ButtonCancel, TextResources.ButtonDelete);
if (action == TextResources.ButtonDelete)
{ } // delete
如果您正在执行视图模型优先导航(s.Xamarin https://developer.xamarin.com/guides/xamarin-forms/enterprise-application-patterns/navigation/#passing_parameters_during_navigation or 乔纳森·耶茨的博客 https://xamarinforms.wordpress.com/2014/11/21/creating-a-xamarin-forms-app-part-6-view-model-first-navigation/)您可以选择将此部分作为导航器服务的一部分。这是一个品味问题