Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF CommandParameter binding to PasswordBox.Password

Tags:

binding

wpf

I have a MVVM run treeview. On the top level is an Account object that contains credentials. I have a PasswordBox that can be used to change the account password with a 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 into the PasswordBox and then click Save. The ClickCommand fires, but the parameter is always string.Empty. What am I missing?

like image 300
light Avatar asked May 03 '11 00:05

light


1 Answers

For security reasons, WPF doesn't provide a dependency property for the Password property of PasswordBox (reference 1, 2), so your command parameter binding doesn't work.

You could bind the command argument to PasswordBox, then access the appropriate property from within your command 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 may want to consider other options that do not involve keeping the password in memory as plain text.

Hope this helps,
Ben

like image 78
Ben Gribaudo Avatar answered Oct 06 '22 22:10

Ben Gribaudo