你想在 viewModel 中使用 Command 来达到如下结果吗?
首先,您需要创建AbstractViewModel。
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Acr.UserDialogs;
namespace MyCusListview
{
public abstract class AbstractViewModel : INotifyPropertyChanged
{
protected AbstractViewModel(IUserDialogs dialogs)
{
this.Dialogs = dialogs;
}
protected IUserDialogs Dialogs { get; }
protected virtual void Result(string msg)
{
this.Dialogs.Alert(msg);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
然后实现这个抽象类,不要忘记在你的视图模型构造函数中添加IUserDialogs dialogs。然后推送dialogs.PromptAsync,即可在input.Text得到结果。
public class PersonsViewModel: AbstractViewModel
{
public ObservableCollection<Person> persons { get; set; }
public static ObservableCollection<Person> selectItems { get; set; }
public ICommand TextChangeCommand { protected set; get; }
public PersonsViewModel(INavigation navigation, IUserDialogs dialogs, ContentPage page):base(dialogs)
{
TextChangeCommand = new Command<Person>(async (key) =>
{
var input = await dialogs.PromptAsync("What is your email?", "Confirm Email", "Confirm", "Cancel");
if (input.Ok)
{
Console.WriteLine("Your email is" + input.Text);
}
});
}
}
当你在后台代码中绑定viewModel时,你只需要在初始化viewmodel的时候使用下面的代码。
public MainPage()
{
InitializeComponent();
personsViewModel = new PersonsViewModel(Navigation, UserDialogs.Instance, this);
this.BindingContext = personsViewModel;
}
这是运行结果。