2011-03-04 68 views
1

我遇到了Treeview導致我瘋狂的問題!!!WPF TreeView無法加載TreeViewItems,直到父窗口展開

我的TreeView的數據綁定到一個對象模型是3個層次深,並且採用了HierarchicalDataTemplate定義什麼應顯示爲每個級別:

公司
+分枝
- + - 聯繫

我想使一個特定的接觸所選擇的節點,這是我正在做這樣的(接觸是從所述數據綁定對象模型中的對象):

Dim companyTreeViewItem As TreeViewItem = Me.AgentTreeView.ItemContainerGenerator.ContainerFromItem(contact.Branch.Company) 
Dim branchTreeViewItem As TreeViewItem = companyTreeViewItem.ItemContainerGenerator.ContainerFromItem(contact.Branch) 
Dim contactTreeViewItem As TreeViewItem = branchTreeViewItem.ItemContainerGenerator.ContainerFromItem(contact) 

如果我展開樹狀視圖,以便將要選擇的節點可見(然後去選擇其他內容),但是如果在展開任何節點之前運行它,branchTreeViewItem將返回爲Nothing(null)。

任何想法如何我可以到我的聯繫對象的TreeViewItem並將其設置爲選中?

EDIT

用於填充樹視圖只是設置控制的DataContext的代碼:

Me.DataContext = New ObjectModel.ObservableCollection(Of DAL.Company)(From c In entities.Companies.Include("Branches").Include("Branches.Contacts") Order By c.CompanyName) 

樹形視圖然後有一個簡單的結合

<TreeView ItemsSource="{Binding}" VirtualizingStackPanel.IsVirtualizing="False" > 
+0

你介意張貼的填充TreeView控件的代碼? – louisgab 2011-03-04 15:44:33

+0

@louisgab,我已更新帖子以包含填充TreeView的代碼。 – Darren 2011-03-04 17:17:44

回答

3

適當溶液將使用MVVM併爲TreeView中的每個項目創建視圖模型IsSelectedIsExpanded屬性綁定到相應的TreeViewItem屬性。然後,您將可以操作IsExpandedIsSelected狀態,而無需使用物品容器生成器進行撥號。

但你也可以做到以下幾點(對不起,我的代碼將在C#):

TreeViewItem companyTreeViewItem = (TreeViewItem)AgentTreeView.ItemContainerGenerator.ContainerFromItem(contact.Branch.Company); 
companyTreeViewItem.IsExpanded = true; 

companyTreeViewItem.ItemContainerGenerator.StatusChanged += (o, e) => { 
    if (companyTreeViewItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) 
    { 
     TreeViewItem branchTreeViewItem = (TreeViewItem) companyTreeViewItem.ItemContainerGenerator.ContainerFromItem(contact.Branch); 
     branchTreeViewItem.IsExpanded = true; 

     branchTreeViewItem.ItemContainerGenerator.StatusChanged += (o1, e1) => { 
      if (branchTreeViewItem.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) 
      { 
       TreeViewItem contactTreeViewItem = (TreeViewItem) branchTreeViewItem.ItemContainerGenerator.ContainerFromItem(contact); 
       contactTreeViewItem.IsSelected = true; 
      } 
     }; 
    } 
};