2

我正在尝试使用 HierarchicalDataTemplate(s) 将复杂的数据结构绑定到 WPF TreeView。数据集合作为 MyObject 的 IList 存储在我的 ViewModel 中 - MyObject 有几个属性,其中一些属性是它们自己的列表。

我试图实现的输出类似于:

+ MyObject 1 <br>
  + List1 <br>
    - List 1 Object 1 <br>
    - List 1 Object 2 <br>
  + List2 <br>
    - List 2 Object 1 <br>
    - List 2 Object 2 <br>
+ MyObject 2 <br>
  + List1 <br>
    - List 1 Object 1 <br>
    - List 1 Object 2 <br>
  + List2 <br>
    - List 2 Object 1 <br>
    - List 2 Object 2 <br>

但是,我似乎无法获得我所见过的复合集合,其中提到了一些工作的地方-

4

1 回答 1

3

我只是做了类似的事情。不幸的是,您不能直接执行此操作,因为 TreeViewItem 只接受一个集合作为其 ItemsSource。

我所做的是创建一个模型,以 TreeView 所需的方式公开内容。

public class MyObjectWrapper
{
  public MyObject Target {get;set;}
  public IEnumerable MyLists
  {
    get
    {
      yield return Target.List1;
      yield return Target.List2;
    } 
  }
}

其中 MyObject 定义为:

public class MyObject
{
    public List1CollectionType List1 {get;private set;}
    public List2CollectionType List2 {get;private set;}
}

然后你的绑定

  • TreeViewItem : MyObjectWrapper
    • ItemsSource : MyLists
    • TreeViewItem : List1CollectionType
      • ItemsSource : {Binding} (binds directly to the datacontext)
    • TreeViewItem : List2CollectionType
      • ItemsSource : {Binding}

You'll need a DataTemplate for MyObjectWrapper, List1CollectionType, and List2CollectionType.

于 2010-12-06T14:02:22.613 回答