如何创建一个只接受数字的输入范围的PasswordBox?

Dav*_*Dev 5 c# xaml windows-phone-7 windows-phone-8

这似乎是Windows Phone中的一个明显的疏忽.该<PasswordBox />控件不允许指定InputScope.

我需要将PasswordBox自定义密码输入屏幕(例如图像和按钮)显示为一部分,并显示数字小键盘以仅允许数字输入.

Coding4Fun PasswordInputPrompt允许数字输入,但它不可自定义,因为我不能围绕它构建自定义布局,它只允许Title&Message值.

我有什么方法可以做到这一点吗?

jac*_*ley 7

您最好只创建自己的用户控件.

xaml看起来像:

<Grid x:Name="LayoutRoot">
    <TextBox x:Name="PasswordTextBox" InputScope="Number" MaxLength="{Binding MaxLength, ElementName=UserControl}" KeyUp="PasswordTextBox_KeyUp"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

并且背后的代码可能是这样的:

public partial class NumericPasswordBox : UserControl
{
    #region Password 

    public string Password
    {
        get { return (string)GetValue(PasswordProperty); }
        set { SetValue(PasswordProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Password.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty PasswordProperty =
        DependencyProperty.Register("Password", typeof(string), typeof(NumericPasswordBox), new PropertyMetadata(null));

    #endregion

    #region MaxLength

    public int MaxLength
    {
        get { return (int)GetValue(MaxLengthProperty); }
        set { SetValue(MaxLengthProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MaxLength.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MaxLengthProperty =
        DependencyProperty.Register("MaxLength", typeof(int), typeof(NumericPasswordBox), new PropertyMetadata(100));

    #endregion

    public NumericPasswordBox()
    {
        InitializeComponent();
    }

    private void PasswordTextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        Password = PasswordTextBox.Text;

        //replace text by *
        PasswordTextBox.Text = Regex.Replace(Password, @".", "?");

        //take cursor to end of string
        PasswordTextBox.SelectionStart = PasswordTextBox.Text.Length;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以根据需要自定义您想要的所有内容,使用示例中显示的MaxLength等依赖项属性.

  • 看代码,这根本行不通.密码属性将填充● (3认同)