MVVM模型视图模型通信模型、视图、通信、MVVM

2023-09-04 01:16:01 作者:、虚情假意,何必称兄道弟

我有一个简单的场景,其中一个视图,视图模型和一个自定义类型的类。

I have a simple scenario with a View, a ViewModel and a custom type 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;

}

在视图模型我有一个Person属性:

In the ViewModel I have a Person property:

private Model.Person person;

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

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

在我看来,我有一个绑定到Person.name一个文本框

In my View I have a textbox that is bound to Person.name

所以视图模型不执行设置方法,因为Person对象仍然是相同的......所执行的一套方法,在 Model属性

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.

我希望让用户改变人的姓名和拨打电话,以另一种方法(通过搜索Web服务和其他的东西......),我觉得这个功能应该是在视图模型。

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.

我使用Messenger在MVVM光工具包不同的ViewModels之间的意见和的ViewModels之间的通信。

I'm using Messenger from MVVM Light toolkit to communicate between different viewmodels and between views and viewmodels.

现在我不知道我是否应该使用调解过这个,或者我应该知道的另一种方式来解决这个问题。

Now I don't know if I should use a mediator too for this or if I should know another way to solve this.

推荐答案

刚刚订阅您的视图模型的人的PropertyChanged事件并检查名称属性,或任何你想要做的:

Just subscribe to the PropertyChanged event of the Person in your ViewModel and check for the "Name" property, or whatever you wanna do:

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

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