如果是這樣的樹,那麼你就需要家長的名單,但只有一個參考親:
public class Item
{
public Item()
{
_col = new ObservableCollection<Item>();
_col.CollectionChanged +=
new NotifyCollectionChanged(ItemChildren_CollectionChanged);
}
public Header { get; set; }
public ObservableCollection<Item> ItemChildren
{ get { return _col; } }
public Item Parent { get { return _parent; } }
private void ItemChildren_CollectionChanged(
object sender,
NotifyCollectionChangedEventArgs e)
{
// for all newly added items: item._parent = this;
// for all removed items: item._parent = null;
}
private Item _parent;
private ObservableCollection<Item> _col;
}
該解決方案比更復雜的是什麼你開始。父對象必須跟蹤其子對象,並確保每次將子對象添加到子對象的父對象都設置爲它。
我一直在輸入這段代碼,沒有語法檢查,但它點擊。您可以在本文中找到幾乎相同問題的完整源代碼:How to Implement Collection Property to Contain Unique Objects。
編輯:請注意Item
上面代碼中的類不允許調用者設置ItemChildren
集合。該集合由Item實例創建並提供,並且不允許任何人對其進行更改。但是任何人都可以在其中添加/刪除項目。還有一件事是項目處理新添加的子項目的方式 - 如果有人試圖添加具有非空父項引用的項目,您可以自由扔InvalidOperationException
!這將確保你的結構仍然是樹。例如,如果參數已經是當前節點的祖先,則XmlNode
類(System.Xml
)從AppendChild
方法拋出InvalidOperationException
方法。當Item
有機會驗證添加到它的元素時,可能性是無止境的。
非常感謝。那正是我正在尋找的! – Kevin