5

我正在使用 Xamarin.Forms 并希望有一个纯数字键盘供我的用户使用 PIN 登录。

我可以用来Xamarin.Forms.Entry.Keyboard = Keyboard.Numeric强制使用数字键盘,这适用于 iOS、Android 和 UWP 手机。但是,当用户在 UWP 平板电脑(如 Microsoft Surface)上运行相同的应用程序时,它会显示完整的键盘,其中包括字符和数字。

我希望数字键盘成为使数据验证更加简单和安全的唯一输入选项。

我知道我可以轻松地进行验证,因为文本更改以确保仅存在数字,但是有没有办法只Xamarin.Forms.Entry在 UWP 平台上的软键盘中显示数字键盘?

4

1 回答 1

4

所以我自己想出了这个,并想为未来的开发人员发布答案。这个用例来自在 UWP 平板电脑上显示软键盘,因为Xamarin.Forms.Entry使用Windows.UI.Xaml.Controls.TextBox. 您可以更改InputScopeTextBox更改 UWP 中的键盘,如文档中所示。

当然,我犯了一个常见错误,即没有完全阅读文档,而是直接跳到可用的键盘上。在文档中,开头有一条重要的线:

重要上 的InputScope属性PasswordBox仅支持PasswordNumericPin values。任何其他值都将被忽略。

哦,快!TextBox当我们真的想PasswordBox为 UWP使用 a 时,我们正在使用 a 。这可以通过 CustomRenderer 和自定义条目轻松实现,如下所示:

自定义条目:

public class MyCustomPasswordNumericEntry: Xamarin.Forms.Entry
{
}

自定义渲染器:

public class PasswordBoxRenderer : ViewRenderer<Xamarin.Forms.Entry, Windows.UI.Xaml.Controls.PasswordBox>
{
    Windows.UI.Xaml.Controls.PasswordBox passwordBox = new Windows.UI.Xaml.Controls.PasswordBox();
    Entry formsEntry;
    public PasswordBoxRenderer()
    {
        var scope = new InputScope();
        var name = new InputScopeName();

        name.NameValue = InputScopeNameValue.NumericPin;
        scope.Names.Add(name);

        passwordBox.InputScope = scope;
    }

    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);

        if (Control == null)
        {
            SetNativeControl(passwordBox);
        }

        if(e.NewElement != null)
        {
            formsEntry = e.NewElement as Entry;

            passwordBox.PasswordChanged += TextChanged;
            passwordBox.FocusEngaged += PasswordBox_FocusEngaged;
            passwordBox.FocusDisengaged += PasswordBox_FocusDisengaged;
        }

        if(e.OldElement != null)
        {
            passwordBox.PasswordChanged -= TextChanged;
        }
    }

    private void PasswordBox_FocusDisengaged(Windows.UI.Xaml.Controls.Control sender, Windows.UI.Xaml.Controls.FocusDisengagedEventArgs args)
    {
        formsEntry.Unfocus();
    }

    private void PasswordBox_FocusEngaged(Windows.UI.Xaml.Controls.Control sender, Windows.UI.Xaml.Controls.FocusEngagedEventArgs args)
    {
        formsEntry.Focus();
    }

    private void TextChanged(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        formsEntry.Text = passwordBox.Password;
    }
}

最后确保我们只注册了 CustomRenderer:

[assembly: Xamarin.Forms.Platform.UWP.ExportRenderer(typeof(MyCustomPasswordNumericEntry), typeof(PasswordBox.UWP.PasswordBoxRenderer))]

现在我们MyCustomPasswordNumericEntryXamarin.Forms.Entry在所有平台上使用 a,但将Windows.UI.Xaml.Controls.PasswordBox在 UWP 上使用 a。我还转发了基本事件以使一切正常,但如果 Xamarin.Forms.Entry.TextChanged 属性上的验证有更改Xamarin.Forms.Entry,您还需要OnElementPropertyChanged()更新方法。PasswordBox

于 2017-03-06T19:02:14.157 回答