TOC

This article has been localized into Chinese by the community.

基本控制項:

PasswordBox 控件

要在 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>

你可以看到,字符现在都显示为 X,而且我最多只能在文本框里输入 6 个字符了。

PasswordBox 与绑定

当你需要从 PasswordBox 获得密码,你可以在逻辑代码里使用 Password 属性。然而,为了安全,Password 属性没有作为依赖属性实现,也就是说你不能绑定到它。

这不一定会影响到你——就像上文所说,你仍旧可以在逻辑代码里读取密码。但如果你想实现 MVVM 或者你就是喜欢数据绑定,这里有另一个解决方案。你可以在这里读到更详细的内容: http://blog.functionalfun.net/2008/06/wpf-passwordbox-and-data-binding.html


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!