开发者

MVVM Model to ViewModel communication

I have a simple scenario with a View, a ViewModel and a custom type class.

The model class is something like:

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:

private Model.Person person;

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

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

In开发者_Python百科 my View I have a textbox that is bound to 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.

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.

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.


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
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜