IsPrimary
1 つがプライマリになった場合に他のアイテムに何が起こるかを決定するのは、ビジネス オブジェクトの責任です。したがって、フラグを管理する何らかのオブジェクトが必要です。
ただし、それを行う場合(カスタムコンテナタイプ、メディエーターなど)、変更を仲介する何かが必要です
例えば
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
}