开发者

WPF - XAML Treeview to Generic.List binding

开发者 https://www.devze.com 2023-01-30 15:27 出处:网络
I am trying to bind an IList to a WPF TreeView in a hierarchal display. Here is my object: public class TeamsTreeViewItem

I am trying to bind an IList to a WPF TreeView in a hierarchal display. Here is my object:

public class TeamsTreeViewItem
 {
  public string DisplayValue { get; set; }
  public string KeyValue { get; set; }

  readonly List<TeamsTreeViewItem> children = new List<TeamsTreeViewItem> ();

  public IList<TeamsTreeViewItem> Children
  {
   get
   {
    return children;
   }
  }

  public override string ToString ()
  {
   return DisplayValue;
  }
 }

I don't know how many children a particular object will have, and the children might have children too.

I am fussing around with my HierarchialDataTemplate, but not being successful:

    <TreeView Canvas.Left="263" Canvas.Top="12" Height="200" Name="TeamTreeView" Width="120">
        <TreeView.Resources>
            <HierarchicalDataTemplate  DataType="{x:Type local:TeamsTreeViewItem}" ItemsSource="{Binding DisplayValue}" >
                <TextBlock Text="{Binding DisplayValue}"/>
            </HierarchicalDataTemplate>
            <HierarchicalDataTemplate  DataType="{x:Type local:TeamsTreeViewItem}" ItemsSource="{Binding Children}" >
                <TextBlock Text="{Binding DisplayValue}"开发者_C百科/>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>

Any suggestions?


You need to apply the ItemsSource to the children like so:

<HierarchicalDataTemplate DataType="{x:Type local:TeamsTreeViewItem}" ItemsSource="{Binding Path=Children}">
    <TextBlock Text="{Binding DisplayValue}"/>
</HierarchicalDataTemplate>

I applied this DataTemplate based on the DataType, that way if the children are of the same type (TeamsTreeViewItem) is should automatically apply it to any item it finds of that type, even if it is a child, grandchild, or great great great .... grandchild. Just make sure to include the namespace (denoted here as "local") that the TeamsTreeViewItem is defined in.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号