Xamarin.Forms.UWP仅限软键盘上的数字键盘

Bre*_*ate 5 xamarin.forms uwp xamarin.uwp

我正在使用Xamarin.Forms并希望我的用户只能使用数字键盘来使用PIN登录.

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

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

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

Bre*_*ate 4

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

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

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

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

自定义条目:

public class MyCustomPasswordNumericEntry: Xamarin.Forms.Entry
{
}
Run Code Online (Sandbox Code Playgroud)

自定义渲染器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后确保我们只注册 CustomRenderer:

[assembly: Xamarin.Forms.Platform.UWP.ExportRenderer(typeof(MyCustomPasswordNumericEntry), typeof(PasswordBox.UWP.PasswordBoxRenderer))]
Run Code Online (Sandbox Code Playgroud)

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