为了在 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 属性未实现为依赖项属性,这意味着您无法绑定到它。