如果用户在WPF中键入任何内容,请检查PasswordBox

时间:2014-03-02 13:05:43

标签: c# wpf mvvm passwords passwordbox

我正在使用PasswordBox并且我想在用户输入任何内容时检测到,如果是,我需要将Button状态更改为启用。如何检查用户是否输入任何内容 在PasswordBox

它的行为与TextBox不同,因为您无法将其绑定到文本 当用户输入任何东西引发一些事件。有什么想法吗?

我尝试过以下代码,但是我收到了错误:

<PasswordBox>
    <i:Interaction.Triggers>
        <EventTrigger EventName="KeyDown">
            <si:InvokeDataCommand Command="{Binding MyCommand}" />
        </EventTrigger>
    </i:Interaction.Triggers>  
</PasswordBox>

2 个答案:

答案 0 :(得分:3)

您可以通过Interactions使用PasswordChanged事件,如下所示:

<强> XAML

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<PasswordBox BorderBrush="#FFB0B1AB"
             Width="100"
             Height="25"
             VerticalAlignment="Bottom">

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="PasswordChanged">
            <i:InvokeCommandAction Command="{Binding PasswordChangedCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</PasswordBox>

<强> RelayCommand

private ICommand _passwordChangedCommand = null;

public ICommand PasswordChangedCommand
{
    get
    {
        if (_passwordChangedCommand == null)
        {
            _passwordChangedCommand = new RelayCommand(param => this.PasswordChanged(), null);
        }

        return _passwordChangedCommand;
    }
}

private void PasswordChanged()
{
    // your logic here
}

<强> Some useful links

PasswordBox in WPF Tutorial

Binding to PasswordBox in WPF (using MVVM)

How to bind to a PasswordBox in MVVM

答案 1 :(得分:2)

您可以使用密码箱中字符串更改时触发的PasswordChanged事件:

XAML部分:

<PasswordBox Name="pwdBox" PasswordChanged="pwdBox_PasswordChanged" />
<Button Name="someButton" IsEnabled="False" Click="someClickEvent" />

C#Part:

    private void pwdBox_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if(String.IsNullOrWhiteSpace(pwdBox.Password)
          somebutton.IsEnabled = false;
        else
          somebutton.IsEnabled = true;
    }

请注意MSDN说

  

获取Password属性值时,将密码作为纯文本显示在内存中。要避免这种潜在的安全风险,请使用SecurePassword属性将密码作为SecureString获取。

因此,以下代码可能是首选:

    private void pwdBox_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if (pwdBox.SecurePassword.Length == 0)
        {
            btn.IsEnabled = false;
        }
        else
        {
            btn.IsEnabled = true;
        }
    }

如果您只能访问viewModel,那么您可以使用附加属性,以便创建可绑定密码或securepassword,如in this example