2013-05-21 39 views
0

我的問題如下: 我有一個treeView,它綁定到ItemsSource。 SelectedItem綁定 我ViewModel稱爲SelectedItem屬性。在TreeView中獲取父列表

的的ItemsSource爲建立這樣的:

public class Item 
{ 
     public Header { get; set; } 
     public ObservableCollection<Item> ItemChildren { get; set; } 
. 
. 
. 
} 

我想刪除,重新排序...的項目。所以我需要SelectedItem的父列表來做到這一點。我可以研究該項目的所有列表,但項目可以存在兩次,對於分隔符項目可以爲空。

有誰知道我怎麼能得到所選項的父列表?

非常感謝你!

問候, 凱文

回答

1

如果是這樣的樹,那麼你就需要家長的名單,但只有一個參考親:

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有機會驗證添加到它的元素時,可能性是無止境的。

+0

非常感謝。那正是我正在尋找的! – Kevin