从ViewModel通信到View

时间:2014-02-11 19:43:16

标签: mvvm properties bind

我遇到需要从ViewModel通信到View的情况,以防发生更改。这里的问题是,我想要更新的属性没有DependencyProperty,我已经设法通过打破一点MVVM模式规则,从View“绑定(不是真的但是......)”从View到VM并简单地在代码后面添加一个事件:

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

这很有效。问题是当我想在VM中发生更改时在View上更新此属性。甚至可能有这种联系吗?

2 个答案:

答案 0 :(得分:2)

您可以在登录视图中创建GetCredential()方法,并且可以在ViewModel中从此方法获取更新的值。

实施将像

<强> View.cs

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

您需要凭据

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

<强> ViewModel.cs

在提交按钮命令处理程序上,您可以从视图中获取值

 Credential credential = View.GetCredential();

答案 1 :(得分:1)

在ViewModel上实现INotifyPropertyChanged