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?
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);
}
}
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
来源:https://stackoverflow.com/questions/7995517/pocos-and-multiple-viewmodels-pointing-to-the-same-poco