简体   繁体   English

MVVM Model 到 ViewModel 通信

[英]MVVM Model to ViewModel communication

I have a simple scenario with a View, a ViewModel and a custom type class.我有一个带有 View、ViewModel 和自定义类型 class 的简单场景。

The model class is something like: model class 类似于:

public class Person : Validation.DataError, INotifyPropertyChanged
{
    #region INotifyProperty

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion


    public global::System.String name
    {
        get
        {
            return _name;
        }
        set
        {
            _name= value;
            RaisePropertyChanged("name");
        }
    }
    private global::System.String _name;

} }

In the ViewModel I have a Person property:在 ViewModel 我有一个 Person 属性:

private Model.Person person;

        public Model.Person Person
        {
            get
            {
                return person;
            }
            set 
            {
                this.person= value;

                this.RaisePropertyChanged("Person");
                this.SavePersonCommand.OnCanExecuteChanged();
            }
        }

In my View I have a textbox that is bound to Person.name在我的视图中,我有一个绑定到 Person.name 的文本框

So the ViewModel is not executing the set method because the Person object is still the same... it is executing the set method in the Model property .所以 ViewModel 没有执行set 方法,因为 Person object 仍然相同......它正在执行Model 属性中的 set 方法。

I want to let the user change the person name and make a call to another method (search through a web service and other stuff...) and I think this functionality should be in the ViewModel.我想让用户更改人名并调用另一种方法(搜索 web 服务和其他东西......),我认为这个功能应该在 ViewModel 中。

I'm using Messenger from MVVM Light toolkit to communicate between different viewmodels and between views and viewmodels.我正在使用 MVVM Light 工具包中的 Messenger 在不同的视图模型之间以及视图和视图模型之间进行通信。

Now I don't know if I should use a mediator too for this or if I should know another way to solve this.现在我不知道我是否也应该为此使用调解器,或者我是否应该知道另一种解决方法。

Just subscribe to the PropertyChanged event of the Person in your ViewModel and check for the "Name" property, or whatever you wanna do:只需在 ViewModel 中订阅 Person 的 PropertyChanged 事件并检查“Name”属性,或者您想做的任何事情:

Person.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Person_PropertyChanged);

void Person_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    if(e.PropertyName == "Name")
    {
         //do something
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM