WPF 入门教程密码框控件

为了在 WPF 中编辑常规文本,我们有 TextBox,但是如何编辑密码呢?功能非常相似,但我们希望 WPF 在输入密码时显示实际字符以外的其他内容,以防止八卦的人偷偷看你。为此,WPF 提供了PasswordBox控件,它与 TextBox 一样易于使用。请允许我举例说明:

<Window x:Class="WpfTutorialSamples.Basic_controls.PasswordBoxSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PasswordBoxSample" Height="160" Width="300">
    <StackPanel Margin="10">
        <Label>Text:</Label>
        <TextBox />
        <Label>Password:</Label>
        <PasswordBox />
    </StackPanel>
</Window>

在截图中,我在两个文本框中输入了完全相同的文本,但在密码版本中,字符被替换为点。您实际上可以使用PasswordChar属性控制使用哪个字符而不是真实字符:

<PasswordBox PasswordChar="X" />

在这种情况下,将使用字符 X 而不是点。如果您需要控制密码的长度,可以使用MaxLength属性:

<PasswordBox MaxLength="6" />

我在这个更新的例子中使用了这两个属性:

<Window x:Class="WpfTutorialSamples.Basic_controls.PasswordBoxSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="PasswordBoxSample" Height="160" Width="300">
    <StackPanel Margin="10">
        <Label>Text:</Label>
        <TextBox />
        <Label>Password:</Label>
        <PasswordBox MaxLength="6" PasswordChar="X" />
    </StackPanel>
</Window>

密码框和绑定

当您需要从 PasswordBox 获取密码时,您可以使用Code-behind 中的Password属性。但是,出于安全原因,Password 属性未实现为依赖项属性,这意味着您无法绑定到它。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值