【问题标题】:Two Lists as children in a WPF TreeViewWPF TreeView 中作为子项的两个列表
【发布时间】:2014-01-07 20:38:34
【问题描述】:

我有一个 WPF TreeView,它绑定到一个对象列表,其中每个对象都有多个列表。

public List<OwnerClass> OwnerClasses {get; set;}

public class OwnerClass
{
    public List<SomeObject> SomeObjects { get; set; }
    public List<OtherObject> OtherObjects { get; set; }
}

我正在寻找一种方法将两个列表都显示为父级的子级。

像这样:

> Owner1
   |
   + SomeObject 1
   + SomeObject 2
   + SomeObject 3
   + OtherObject 1
   + OtherObject 2
   + OtherObject 3
   + OtherObject 4

> Owner2
   |
   + SomeObject 1
   + SomeObject 2
   + SomeObject 3
   + OtherObject 1
   + OtherObject 2
   + OtherObject 3
   + OtherObject 4

我想要树视图功能,但我想要并排的子列表。 (并且每一个都是树视图,因为它们又都有列表。)

这可能吗?

【问题讨论】:

  • 创建一个合适的 ViewModel。将您拥有的任何格式的数据转换为可以在HierarchicalDataTemplate 中使用的格式。

标签: c# wpf xaml datatemplate hierarchicaldatatemplate


【解决方案1】:

您可能会创建一个将两个列表“连接”为一个的属性:

public class OwnerClass
{
    public List<SomeObject> SomeObjects { get; set; }
    public List<OtherObject> OtherObjects { get; set; }
    public object AllObjects 
    {
        get
        {
            List<object> list = SomeObjects;
            list.AddRange(OtherObjects);
            return list;
        }
    }
} 

【讨论】:

    【解决方案2】:

    您需要做两件事才能轻松做到这一点。 @DLeh 很好地演示了第一个,尽管我建议在使用 WPF 时使用 ObservableCollection&lt;T&gt; 类而不是 List&lt;T&gt; 类。

    您需要的第二件事是HierarchicalDataTemplate。它就像一个普通的DataTemplate,但它允许你为子节点设置一个来源:

    <HierarchicalDataTemplate DataType="{x:Type YourXmlNamespacePrefix:OwnerClass}" 
        ItemsSource="{Binding AllObjects}">
        <TextBlock Text="{Binding SomePropertyFromObject}"/>
    </HierarchicalDataTemplate>
    

    您可以从 MSDN 上的HierarchicalDataTemplate Class 页面了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多