如何在WPF密码框中显示几秒钟的字符?

Sim*_*mce 13 wpf textbox delay passwordbox

如果用户在密码框中输入1985,将显示四个子弹(●●●●).如何在几秒钟内显示输入的每个字母或数字,然后将其更改为子弹?我想这不能在密码框中完成,但有没有其他方法可以做到这一点?

Ste*_*bob 19

将一个文本框放在密码框的顶部,然后使用一个小的数据绑定和动画.只要打字输入,这个XAML块就会允许文本框可见,但是一旦打字停止,文本框就会消失,只留下显示密码字符的密码框.

    <Window.Resources>
        <Storyboard x:Key="Storyboard1">
            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="textBox">
                <EasingDoubleKeyFrame KeyTime="0" Value="1"/>
                <EasingDoubleKeyFrame KeyTime="0:0:0.6" Value="1"/>
                <EasingDoubleKeyFrame KeyTime="0:0:1.2" Value="0"/>
            </DoubleAnimationUsingKeyFrames>
        </Storyboard>
    </Window.Resources>
    <Window.Triggers>
        <EventTrigger RoutedEvent="TextBoxBase.TextChanged" SourceName="textBox">
            <StopStoryboard BeginStoryboardName="Storyboard1_BeginStoryboard"/>
            <BeginStoryboard x:Name="Storyboard1_BeginStoryboard" Storyboard="{StaticResource Storyboard1}"/>
        </EventTrigger>
    </Window.Triggers>




<PasswordBox x:Name="passwordBox"/>
<TextBox x:Name="textBox"
        Text="{Binding ElementName=passwordBox, Path=Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         Opacity="100"/>
Run Code Online (Sandbox Code Playgroud)

您可以在动画中使用KeyTimes来获得您喜欢的延迟.您还可以更改文本框中的字体设置,以使键入的文本和密码字符更好地排列.

编辑

如果您只想显示键入明文的最后一个字符:

这种情况有点不同,需要更多的复杂性.此方案仅使用窗口上的文本框,而不是密码框.

<TextBox Name="tbxPwd" Margin="20,0" 
         Text="{Binding Path=DisplayedPwd}" />
Run Code Online (Sandbox Code Playgroud)

在窗口(或ViewModel类)的代码隐藏中,您将需要两个属性,ActualPwdDisplayedPwd.文本框绑定到DisplayedPwd属性.

在代码隐藏中,您将需要以下代码:

Private Sub tbxPwd_PreviewKeyDown(sender As Object, e As System.Windows.Input.KeyEventArgs) _
  Handles tbxPwd.PreviewKeyDown

  If e.Key = Key.Back Then
     If ActualPwd.Length > 0 Then
        //Remove the last character.
        ActualPwd = ActualPwd.Substring(0, ActualPwd.Length - 1)
        ShowLastCharacter()
        tbxPwd.CaretIndex = DisplayedPwd.Length
     End If
  End If

End Sub

Private Sub tbxPwd_PreviewTextInput(sender As Object, e As System.Windows.Input.TextCompositionEventArgs) _
  Handles tbxPwd.PreviewTextInput

  ActualPwd &= e.Text
  e.Handled = True

  ShowLastCharacter()

  tbxPwd.CaretIndex = DisplayedPwd.Length

End Sub

Private Sub ShowLastCharacter()
  Dim lastChar As Char = ActualPwd.Substring(ActualPwd.Length - 1)

  //Reset the displayed pwd.
  DisplayedPwd = ""
  For i As Int32 = 0 To ActualPwd.Length - 2
     DisplayedPwd &= "•"
  Next
  DisplayedPwd &= lastChar

End Sub
Run Code Online (Sandbox Code Playgroud)

tbxPwd_PreviewTextInput方法用于检索用户键入的字符.tbxPwd_PreviewKeyDown方法用于检索BackSpace密钥或要检测的任何其他控制字符密钥.

此代码没有延迟,因此它始终以明文形式显示密码字符串的最后一个字符.应该很容易添加一些代码和Timer,以便在延迟一段时间后将最后一个字符更改为pwd字符.

上面的代码尚未经过彻底调试,因此如果用户退出整个密码重新开始,可能会出现问题.

提示:Alt + 0149显示'bullet'密码字符.