MVVM 模型到 ViewModel 的通信
我有一个简单的场景,其中包含一个视图、一个视图模型和一个自定义类型类。
模型类类似于:
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;
}
在 ViewModel 中,我有一个 Person 属性:
private Model.Person person;
public Model.Person Person
{
get
{
return person;
}
set
{
this.person= value;
this.RaisePropertyChanged("Person");
this.SavePersonCommand.OnCanExecuteChanged();
}
}
在我的 View 中,我有一个绑定到 Person.name 的文本框
因此,ViewModel 不会执行 set 方法,因为 Person对象仍然是相同的...它正在执行 Model 属性 中的 set 方法。
我想让用户更改人名并调用另一个方法(搜索 Web 服务和其他内容...),我认为此功能应该位于 ViewModel 中。
我使用 MVVM Light 工具包中的 Messenger 在不同视图模型之间以及视图和视图模型之间进行通信。
现在我不知道我是否也应该使用调解器来解决这个问题,或者我是否应该知道另一种方法来解决这个问题。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需订阅 ViewModel 中 Person 的 PropertyChanged 事件并检查“Name”属性,或者执行您想要执行的任何操作:
Just subscribe to the PropertyChanged event of the Person in your ViewModel and check for the "Name" property, or whatever you wanna do: