0

I have a situation where I need to communicate from a ViewModel to View in case a change happens. The problem here is, the property I want to update does not have a DependencyProperty, and I have managed to get a way around to "bind (not really but..)" it from View to VM by breaking a little the MVVM pattern rules and simply adding in the code-behind an event:

(ViewModelSomething as DataContext).Password = pb.Password;

And this works. The problem is when I want to update this property on a View when a change happens in the VM. Is there even possible a such connection?

jonjohnson
  • 413
  • 1
  • 5
  • 18
  • There is a similar question here: http://stackoverflow.com/questions/1483892/how-to-bind-to-a-passwordbox-in-mvvm. You probably won't like the accepted answer though... – Thomas Levesque Feb 11 '14 at 19:55
  • why can a change to Password happen in a viewmodel without user interaction? – blindmeis Feb 12 '14 at 06:32

2 Answers2

2

You can create a GetCredential() method in your Login View and you can get the updated values from this method in your ViewModel.

Implementation will be like

View.cs

public Credential GetCredential()
    {
        var credential = new Credential()
        {
            Username = txtUserName.Text,
            Password = txtPassword.Password
        };
        return credential;
    }

You need a Credential class

 public class Credential
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

ViewModel.cs

On Submit button Command Handler you can get values from your View

 Credential credential = View.GetCredential();
Mukesh Rawat
  • 2,047
  • 16
  • 30
1

Implement INotifyPropertyChanged on the ViewModel

Robert Levy
  • 28,747
  • 6
  • 62
  • 94