如何在 Xamarin 中调用按钮单击事件

How can I make a call on button click event in Xamarin

我有服务class

public async Task LoginAsync(string userName, string password)
{
   var model = new
   {
       phoneNum = userName,
       passwordUs = password
   };
   .............
}

Page1.xaml.cs。这就是我调用服务 class

的方式
private ApiServices _apiServices = new ApiServices();
public ICommand LoginCommand { get; set; }
async void btone_Clicked(object sender, EventArgs e)
{
   LoginCommand = new Command(async () => {
      await _apiServices.LoginAsync(txtone.Text, txttwo.Text);
   });
}

看来我的代码有误,所以没有调用服务class

我希望当按钮单击事件时它会调用 LoginAsync

我已经创建了一个 ViewModel,它工作正常,但是我不想通过 ViewModel。 (也许出于某种原因我想检查按钮点击事件的正确位置)。谢谢!

您正在创建命令 - 仅当您想将命令绑定到按钮时才需要,分配事件处理程序时不需要

async void btone_Clicked(object sender, EventArgs e)
{
   LoginCommand = new Command(async () => {
      await _apiServices.LoginAsync(txtone.Text, txttwo.Text);
   });
}

而是直接调用该方法

async void btone_Clicked(object sender, EventArgs e)
{
   await _apiServices.LoginAsync(txtone.Text, txttwo.Text);
}

将此添加到您的 xaml

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="YourNameSpace.LoginPage"
             xmlns:viewmodel="clr-namespace:YourNameSpace.ViewModels">
    <ContentPage.BindingContext>
        <viewmodel:LoginPageViewModel></viewmodel:LoginPageViewModel>
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout>                    
                    <Entry Placeholder="Username" Text="{Binding Username}" />                    
                    <Entry Placeholder="Password" Text="{Binding Password}" /> 
                    <Button Text="Login" Command="{Binding LoginCommand}" />                       
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

将此添加到您的视图模型中

namespace YourNameSpace.ViewModels
{
    public class LoginPageViewModel
    {
        public string Username { get; set; }
        public string Password { get; set; }
        private ApiServices _apiServices = new ApiServices();
        public ICommand LoginCommand
        {
            get
            {
                return new Command(async () =>
                {
                    await _apiServices.LoginAsync(txtone.Text, txttwo.Text);
                });
            }
        }
    }
}