5

每当我单击复选框时,如何取消屏蔽和屏蔽密码框中的密码?我正在使用 C# WPF 模板。

这是我的 .XAML 代码:

<PasswordBox x:Name="passwordBox_password" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Margin="5" Height="25" />
        <CheckBox x:Name="checkBox_showPassword" Grid.Row="3" Grid.Column="1" Margin="5,0,5,5" Content="show password" Checked="checkBox_showPassword_Checked" Unchecked="checkBox_showPassword_Unchecked" />

这是我的 .CS 代码:

private void checkBox_showPassword_Checked(object sender, RoutedEventArgs e)
    {
        // what to do here ?
    }

    private void checkBox_showPassword_Unchecked(object sender, RoutedEventArgs e)
    {
        // what to do here ?
    }

还是有另一种方法可以在 WPF 中做到这一点?

4

3 回答 3

5

It's very simple to do that. First you should to add the value PasswordChar in your PasswordBox:

<PasswordBox Name="PasswordHidden" PasswordChar="•"/>

Next under the PasswordBox tag you should to add a TextBox with Visibility value setted to Hidden:

<TextBox Name="PasswordUnmask" Visibility="Hidden"/>

And a trigger to show / hide the password, for example a simple text or a button. In my case I'm using a simple text.

<TextBlock Name="ShowPassword"/>

Next you need to add 3 different events in the trigger element, for example (this is valid for TextBlock or Image, if you want to use a Button you should to choose another events):

<TextBlock x:Name="ShowPassword" Text="SHOW" PreviewMouseDown="ShowPassword_PreviewMouseDown" PreviewMouseUp="ShowPassword_PreviewMouseUp" MouseLeave="ShowPassword_MouseLeave"/>

The events are PreviewMouseDown PreviewMouseUp and MouseLeave but you can choose the appropriate event for your situation.

Now in your code you need to program the functions:

private void ShowPassword_PreviewMouseDown(object sender, MouseButtonEventArgs e) => ShowPasswordFunction();
private void ShowPassword_PreviewMouseUp(object sender, MouseButtonEventArgs e) => HidePasswordFunction();
private void ShowPassword_MouseLeave(object sender, MouseEventArgs e) => HidePasswordFunction();

private void ShowPasswordFunction()
{
    ShowPassword.Text = "HIDE";
    PasswordUnmask.Visibility = Visibility.Visible;
    PasswordHidden.Visibility = Visibility.Hidden;
    PasswordUnmask.Text = PasswordHidden.Password;
}

private void HidePasswordFunction()
{
    ShowPassword.Text = "SHOW";
    PasswordUnmask.Visibility = Visibility.Hidden;
    PasswordHidden.Visibility = Visibility.Visible;
}
于 2019-05-14T17:15:30.553 回答
3

以下链接将带您找到您正在寻找我的好先生的答案。拉马斯先生在回答方法方面做得很好,所以我宁愿将您重定向到答案:)

在密码框的某些事件上显示密码字符

于 2015-06-25T03:22:22.963 回答
1

我建议使用 MahApps.Metro ...在从 nuget.org 安装之后 ...您必须在 xaml 的头部使用它,例如 xmlns:controls="http://metro.mahapps.com/winf/xaml/控制”

然后......只需将其样式用于您的 PasswordBox 控件

<PasswordBox  Style="{StaticResource MetroButtonRevealedPasswordBox}" />

您甚至可以使用控件更改显示图标的内容:PasswordBoxHelper.RevealButtonContent 附加属性

于 2019-08-17T13:16:49.940 回答