WPF CommandParameter binding to PasswordBox.Password

I have an MVVM run treeview. At the top level is the Account object containing the credentials. I have a PasswordBox that you can use to change your account password using the "Save" button right behind it. The code is as follows and is part of the account level template:

PasswordBox Width="100" x:Name="pbPassword"/>

Button x: Name = "btnSave" Command = "{Binding ClickCommand}" CommandParameter = "{Binding ElementName = pbPassword, Path = Password}" Height = "20" Width = "50"> Save

I put something in the PasswordBox and then click "Save." ClickCommand starts, but the parameter is always string.Empty. What am I missing?

+5
source share
2 answers

For security reasons, WPF does not provide a dependency property for the Password PasswordBox property (ref. 1 , 2 ), therefore, binding command parameters does not work.

You can associate the command argument with PasswordBox, then access the corresponding property from your implementation:

<Button Command="{Binding ClickCommand}" CommandParameter="{Binding ElementName=pbPassword}">

// command implementation
public void Execute(object parameter)
{
    var passwordBox = (PasswordBox)parameter;
    var value = passwordBox.Password;
}

You might want to consider other options that are not related to saving the password in memory as plain text.

Hope this helps,
Ben

+9
source

- PLEASE STOP THE LABELING WHICH ME REFUSES TO THIS, see the comment below, this does not work, but is left so that no one else makes the same mistake -

Sorry old Q, but found an improvement on this

<Button Content="Log On" 
  Command="{Binding LogOnCommand}" 
  CommandParameter="{Binding ElementName=PasswordControl, Path=SecurePassword}" />

SecureString

public override void Execute(object parameter)
{
    _viewModel.LogOnAsync((SecureString)parameter);
}

ui

-1

All Articles