所以我自己想出了这个问题,并想为未来的开发人员发布答案。此用例来自在 UWP 平板电脑上显示软键盘,因为 Xamarin.Forms.Entry 使用了 Windows.UI.Xaml.Controls.TextBox。您可以更改TextBox 的InputScope 以更改UWP 中的键盘,如documentation 所示。
当然,我犯了一个常见的错误,即没有完全阅读文档,而是直接跳到可用的键盘上。在文档的开头有一个重要的行:
重要PasswordBox 上的InputScope 属性仅支持Password 和NumericPin values。任何其他值都会被忽略。
哦,快!当我们真的想为 UWP 使用 PasswordBox 时,我们使用的是 TextBox。这可以通过 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))]
现在我们的MyCustomPasswordNumericEntry 将在所有平台上使用Xamarin.Forms.Entry,但在UWP 上将使用Windows.UI.Xaml.Controls.PasswordBox。我还转发了 Xamarin.Forms.Entry 上的基本事件以使一切正常,但如果 Xamarin.Forms.Entry.TextChanged 属性上的验证发生更改,您还需要让 OnElementPropertyChanged() 方法更新 PasswordBox .