Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to bind to a PasswordBox in MVVM
    text
    copied!<p>I have come across a problem with binding to a PasswordBox. It seems it's a security risk but I am using the MVVM pattern so I wish to bypass this. I found some interesting code here (has anyone used this or something similar?)</p> <p><a href="http://www.wpftutorial.net/PasswordBox.html" rel="noreferrer">http://www.wpftutorial.net/PasswordBox.html</a></p> <p>It technically looks great, but I am unsure of how to retrieve the password. </p> <p>I basically have properties in my <code>LoginViewModel</code> for <code>Username</code> and <code>Password</code>. <code>Username</code> is fine and is working as it's a <code>TextBox</code>.</p> <p>I used the code above as stated and entered this</p> <pre><code>&lt;PasswordBox ff:PasswordHelper.Attach="True" ff:PasswordHelper.Password="{Binding Path=Password}" Width="130"/&gt; </code></pre> <p>When I had the <code>PasswordBox</code> as a <code>TextBox</code> and <code>Binding Path=Password</code> then the property in my <code>LoginViewModel</code> was updated.</p> <p>My code is very simple, basically I have a <code>Command</code> for my <code>Button</code>. When I press it <code>CanLogin</code> is called and if it returns true it calls <code>Login</code>.<br> You can see I check my property for <code>Username</code> here which works great. </p> <p>In <code>Login</code> I send along to my service a <code>Username</code> and <code>Password</code>, <code>Username</code> contains data from my <code>View</code> but <code>Password</code> is <code>Null|Empty</code></p> <pre><code>private DelegateCommand loginCommand; public string Username { get; set; } public string Password { get; set; } public ICommand LoginCommand { get { if (loginCommand == null) { loginCommand = new DelegateCommand( Login, CanLogin ); } return loginCommand; } } private bool CanLogin() { return !string.IsNullOrEmpty(Username); } private void Login() { bool result = securityService.IsValidLogin(Username, Password); if (result) { } else { } } </code></pre> <hr> <p>This is what I am doing</p> <pre><code>&lt;TextBox Text="{Binding Path=Username, UpdateSourceTrigger=PropertyChanged}" MinWidth="180" /&gt; &lt;PasswordBox ff:PasswordHelper.Attach="True" ff:PasswordHelper.Password="{Binding Path=Password}" Width="130"/&gt; </code></pre> <p>I have my <code>TextBox</code>, this is no problem, but in my <code>ViewModel</code> the <code>Password</code> is empty.</p> <p>Am I doing something wrong or missing a step?</p> <p>I put a breakpoint and sure enough the code enter the static helper class but it never updates my <code>Password</code> in my <code>ViewModel</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload