如何解决如何从Xamarin表单的ViewModel中获取数字输入
运行命令后,我需要向用户请求一个号码。这需要在视图模型中运行。我已经尝试过ACR.UserDialog,但似乎无法弄清楚如何从viewmodel调用它。
类似这样的东西:
void RemoveItem()
{
int intQuantity = (dialog from user to get the quantity);
}
谢谢!
解决方法
samples展示了如何做到这一点
// Dialogs is an IUserDialogs that you pass to your VM from your page
// using UserDialogs.Instance
var result = await Dialogs.PromptAsync(new PromptConfig()
.SetTitle("Max Length Prompt")
.SetPlaceholder("Maximum Text Length (10)")
.SetInputMode(InputType.Name)
.SetMaxLength(10));
// result.Text will contain the user's response
,
是否要在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;
}
这是运行结果。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。