问题描述
一个人怎么会去处理这样的情况?具有具有到相同POCO对象的引用多个视图模型。视图模型A更新的POCO ...现在视图模型B需要知道这个不知何故?
How would one go about handling a situation like this? Having more than one ViewModel having a reference to the same POCO object. ViewModel A updates the POCO... now ViewModel B needs to know about this somehow?
推荐答案
假设你的POCO不能实施 INotifyPropertyChanged的
,你可以使用当POCO改变格局,以提醒其他视图模型:
Assuming that your POCO can't implement INotifyPropertyChanged
, you could use a mediator pattern to alert other view models when a POCO is changed:
public interface ICareWhenAModelChanges<T>
{
void ModelUpdated(T updatedModel);
}
public class ModelChangeMediator<T>
{
private List<ICareWhenAModelChanges<T>> _listeners = new List<ICareWhenAModelChanges<T>>();
public void Register(ICareWhenAModelChanges<T> listener)
{
_listeners.Add(listener);
}
public void NotifyThatModelIsUpdated(T updatedModel)
{
foreach (var listener in _listeners) listener.ModelUpdated(updatedModel);
}
}
您的视图模型则可以实现 ICareWhenAModelChanges< T>
接口,与调解员的共享实例注册本身(或者通过一个单身,或者更好,某种DI / IoC框架的收购),做任何它需要在 ModelUpdated
法
Your view model can then implement the ICareWhenAModelChanges<T>
interface, register itself with a shared instance of the mediator (acquired through either a singleton or, better, some kind of DI/IoC framework) and do whatever it needs to in the ModelUpdated
method
这篇关于波苏斯和多个的ViewModels指向相同POCO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!