WPF TreeView在父扩展之前不加载TreeViewItems

时间:2011-03-04 15:41:03

标签: wpf treeview

我遇到了Treeview的问题让我疯了!!!

我的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并将其设置为选中的?

修改

填充树视图的代码只是设置控件的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" >

1 个答案:

答案 0 :(得分: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;
            }
        };
    }
};