首页 > 解决方案 > 从 Xamarin 的视图页面中的条目获取用户数据

问题描述

在我的 Xamarin 应用程序中,我能够通过Entry从用户那里获取数据并将其绑定到ViewModel.cs中。

但是,现在我想从ViewPage的 Entry 中获取这些用户数据。

下面是 .xml 页面中的 Entry 代码以及我使用 ViewModel 的 Data Biding 的代码(它运行良好)。

我如何也可以通过PageView.xml.cs中的 Entry 获取用户数据。

页面视图.xml

<Entry
    Text="{Binding Email}"
    Keyboard="Email"
    ReturnType="Done"
    FontSize="15"
    Placeholder="Enter Email" >
</Entry>

<Entry
    Text="{Binding Password}"
    Keyboard="Numberic"
    ReturnType="Done"
    FontSize="15"
    IsPassword="true"
    MaxLenght="8"
    Placeholder="Enter Password" >
</Entry>

<Button
    x:Name="SubmitButton"
    Text="Submit" />

PageView.xml.cs

FormDataButton.Clicked += async (sender, args) =>
{
    if (Email != null && Password != null && Password.Lenght == 8)
    {
        // sample code
        var email = Email;
        var password = Password;
    }
    else{
        Console.WriteLine("Error");
    }
}

我在 ViewModel.cs 中使用的数据绑定

private string _Email;
public string Email
{
    get => _Email;
    set => this.RaiseAndSetIfChanged(ref _Email, value);
}

private string _Password;
public string Password
{
    get => _Password;
    set => this.RaiseAndSetIfChanged(ref _Password, value);
}

标签: c#.netxamarin.net-corexamarin.forms

解决方案


如果您的意思是代码隐藏,您只需为控件分配一个名称

<Entry x:Name="MyEntry"
    Text="{Binding Email}"
    Keyboard="Email"
    ReturnType="Done"
    FontSize="15"
    Placeholder="Enter Email" >
</Entry>

然后在后面的代码中,

if (myEntry.Text == "blah") ...

但是,如果您已经在使用数据绑定,那么您可以通过您的 VM 访问该值

if (VM.Email == "blah") ...

推荐阅读