业务对象负责确定如果一个成为主要项目会发生什么其他项目,因此您需要某种管理IsPrimary
标志的对象。
但是,您这样做(自定义容器类型、调解器等)您需要一些东西来调解更改
例如
public class Mediator
{
IList<Contact> _contacts = null;
public Mediator(IList<Contact> contacts)
{
_contacts = contacts;
foreach(var c in contacts)
{
c.PropertyChanged += ContactPropertyChanged;
}
}
private bool _isChanging = false;
private void ContactPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var current = sender as Contact;
if(e.PropertyName == "IsPrimary" && !_isChanging && current.IsPrimary)
{
_isChanging = true;
foreach(var c in _contacts.Where(x => x != current)
{
c.IsPrimary = false;
}
_isChanging = false;
}
}
}
可能有更好的方法,比如拥有一个容器集合(它自己挂钩 propertychanged 等......还要注意事件处理程序!)
您可以编写一个更通用的模板版本来触发重载(因此您可以轻松地创建子类以创建不同的中介等)
public class Mediator<T>
{
IList<T> _items = null;
public Mediator(IList<T> items, params string[] watchedProperties) { ... etc
protected virtual OnWatchedPropertyChanged(T sender, string PropertyName)
{
}
}
public ContactMediator : Mediator<Contact>
{
public ContactMediator(IList<Contact> contacts, params string[] watchedProperties) { ...
override OnWatchedPropertyChanged(Contact object, string propertyName) { ... etc
}