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