wpf 具有不同类型子节点的Treeview Item

icomxhvb  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(113)

我有三个类,我希望在树视图中表示

public class ConfiguratorObjectViewModel
{
    public string Name { get; set; }
    
    public string Id { get; set; }
        
    public string ParentId { get; set; }
    
    public ObservableCollection<ConfiguratorAttributeViewModel> Attributes { get; set; } 
        
    public ObservableCollection<ConfiguratorObjectFamilyViewModel> Children { get; set; }   
}
public class ConfiguratorObjectFamilyViewModel
{
    public string Name { get; set; }
    
    public string Id { get; set; }
        
    public string ParentId { get; set; }
        
    public ObservableCollection<ConfiguratorObjectViewModel> ConfiguratorObjects { get; set; }  
}
public class ConfiguratorAttributeViewModel
{
    public string Name { get; set; }
    
    public string Id { get; set; }
        
    public string ParentId { get; set; }    
}

这是我的treeview模板

<TreeView ItemsSource="{Binding RootObject}" >
    <TreeView.Resources>
    
    <HierarchicalDataTemplate DataType="{x:Type local:ConfiguratorObjectFamilyViewModel}" ItemsSource="{Binding ConfiguratorObjects}">
            <local:ConfiguratorObjectTreeItem  />
        </HierarchicalDataTemplate>
    
     <HierarchicalDataTemplate DataType="{x:Type local:ConfiguratorObjectViewModel}" ItemsSource="{Binding }" Children>
            <local:ConfiguratorObjectTreeItem  />
        </HierarchicalDataTemplate>   

    </TreeView.Resources>

</TreeView>

这个模板给了我所有的ConfiguratorObjectFamily和所有的ConfoguratorObject项目。我如何扩展它,使ConfiguratorAttribute项应该包含在树中?
我试过通过添加以下组合来扩展模板,但无济于事...

<HierarchicalDataTemplate DataType="{x:Type local:ConfiguratorAttributeViewModel}" ItemsSource="{Binding Attributes}" >
    <local:ConfiguratorObjectTreeItem  />
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:ConfiguratorAttributeViewModel}" >
    <local:ConfiguratorObjectTreeItem  />
</DataTemplate>

请注意,ConfiguratorAttributeViewModel不是层次结构

1tuwyuhd

1tuwyuhd1#

我通过使用复合集合找到了一个解决方案。

public IList Items
{
  get
  {
    return new CompositeCollection()
    {
      new CollectionContainer() { Collection = Children },
      new CollectionContainer() { Collection = Attributes }
    };
  }
}

模板如下:

<HierarchicalDataTemplate DataType="{x:Type local:ConfiguratorObjectViewModel}" ItemsSource="{Binding Items}" >
    <local:ConfiguratorObjectTreeItem  />
</HierarchicalDataTemplate>

<HierarchicalDataTemplate DataType="{x:Type local:ConfiguratorObjectFamilyViewModel}" ItemsSource="{Binding ConfiguratorObjects}">
    <local:ConfiguratorObjectTreeItem  />
</HierarchicalDataTemplate>

<DataTemplate DataType="{x:Type local:ConfiguratorAttributeViewModel}" >
    <local:ConfiguratorObjectTreeItem  />
</DataTemplate>

相关问题