Xamarin 检测输入键 MVVM

Haa*_*ani 2 xaml xamarin xamarin.forms

如何使用 MVVM 方法检测何时按下 Enter 键(或任何其他键)。我是 xamarin 的新手,所以我希望我问的是正确的问题。我的想法是向密码条目添加一个命令。这是正确的方法吗?我可以将已完成事件添加到后端代码,但如何将其链接到我的视图模型?

这是我的 XAML 代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:newApp"
             x:Class="newApp.MainPage">

    <ContentPage.Content>

        <StackLayout Padding="30" Spacing="10" VerticalOptions="Center">

            <Image Source="logo.png" />

            <Entry Text="{Binding Username}" Placeholder="Username"  />

            <Entry Text="{Binding Password}" IsPassword="True" Placeholder="Password" />

            <Label Text="{Binding DisplayMessage}"/>

            <Button Text="Log In" Command="{Binding LogInCommand}"  />

        </StackLayout>

    </ContentPage.Content>
</ContentPage>
Run Code Online (Sandbox Code Playgroud)

这是后端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

    namespace newApp
    {
      public partial class MainPage : ContentPage
      {
          public MainPage()
          {
              InitializeComponent();
              BindingContext = new LoginViewModel();
          }
      }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的 ViewModel

namespace newApp
{
    class LoginViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        string username, password;
        Boolean bol;

        void OnPropertyChanged([CallerMemberName] string name = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnPropertyChanged();
            }
        }

        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                OnPropertyChanged();

                OnPropertyChanged(nameof(DisplayMessage));
            }
        }

        public string DisplayMessage
        {
            get
            {
                if (username != ""){return $"This is your {Username}";}
                else return "";
            }
        }


        void Login()
        {
            if (username == "")
                bol = false;

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ger*_*uis 5

简短的回答是:你不能。该Completed事件就是这样:一个事件。由于事件的工作方式,它们不适合 MVVM 模式。

有几种方法可以解决这个问题。首先,您可以在代码隐藏中捕获事件,然后在属性中的视图模型中触发代码BindingContext。虽然您有点偏离 MVVM 模式,但这是解决这个问题的一种方法。

另一种选择是创建您自己的控件继承并实现一个采用Command. 然后,您可以在内部将事件循环到Command.

但最简单的解决方案可能是创建一个Behavior将您的事件变成Command. 要创建一个Behavior可将其上的任何事件转换为 a 的可重用对象Command,请像这样实现它(完整的实现可以在下面的链接中找到):

public class EventToCommandBehavior : BehaviorBase<View>
{
  public static readonly BindableProperty EventNameProperty =
    BindableProperty.Create ("EventName", typeof(string), typeof(EventToCommandBehavior), null, propertyChanged: OnEventNameChanged);
  public static readonly BindableProperty CommandProperty =
    BindableProperty.Create ("Command", typeof(ICommand), typeof(EventToCommandBehavior), null);
  public static readonly BindableProperty CommandParameterProperty =
    BindableProperty.Create ("CommandParameter", typeof(object), typeof(EventToCommandBehavior), null);
  public static readonly BindableProperty InputConverterProperty =
    BindableProperty.Create ("Converter", typeof(IValueConverter), typeof(EventToCommandBehavior), null);

  public string EventName { ... }
  public ICommand Command { ... }
  public object CommandParameter { ... }
  public IValueConverter Converter { ...  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

对于您的Entry,请像这样附加它:

<Entry Text="{Binding Username}">
  <Entry.Behaviors>
    <local:EventToCommandBehavior EventName="Completed" Command="{Binding CompletedCommand}" />
  </Entry.Behaviors>
</Entry>
Run Code Online (Sandbox Code Playgroud)

在文档中了解有关此内容的更多信息:https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/behaviors/reusable/event-to-command-behavior