Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The tricky part of this solution is having to deal with two collections underneath each node and TreeView's HierarchicalDataTemplate only supports binding to a single ItemsSource.</p> <p>One option is to create a ViewModel that merges the collections into a single class that represents an entry in the TreeView that you can then bind to inside your HierarchicalDataTemplate.</p> <p>First I created my ViewModel class:</p> <pre><code>public class TreeViewEntry { public string Name { get; set; } public IEnumerable&lt;TreeViewEntry&gt; Children { get; set; } public object Model { get; set; } } </code></pre> <p>Then I used a function, some Linq and some recursion to pull all the objects into a single collection:</p> <pre><code>private IEnumerable&lt;TreeViewEntry&gt; OrganizationsToTreeViewEntries(IEnumerable&lt;Organization&gt; orgs) { return (from o in orgs select new TreeViewEntry { Name = o.Name, Model = o, Children = (from u in o.Users select new TreeViewEntry { Name = u.Name, Model = u } ).Concat(OrganizationsToTreeViewEntries(o.Children)) }); } public MainPage() { InitializeComponent(); var items = OrganizationsToTreeViewEntries(existingOrganizationData); OrgTree.ItemsSource = items; } </code></pre> <p>Now that I have a merged ItemsSource it's easy to style my HierarchicalDataTemplate:</p> <pre><code>&lt;UserControl.Resources&gt; &lt;common:HierarchicalDataTemplate x:Key="OrgTemplate" ItemsSource="{Binding Children}"&gt; &lt;StackPanel&gt; &lt;TextBlock Text="{Binding Name}" /&gt; &lt;/StackPanel&gt; &lt;/common:HierarchicalDataTemplate&gt; &lt;/UserControl.Resources&gt; &lt;Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource SampleDataSource}}"&gt; &lt;controls:TreeView x:Name="OrgTree" HorizontalAlignment="Left" Margin="8,8,0,8" Width="225" ItemTemplate="{StaticResource OrgTemplate}" /&gt; &lt;/Grid&gt; </code></pre> <p>You can use a ValueConverter to tweaks things like FontWeight if you want to adjust the visual style of certains elements (for example in my testing I created a ValueConverter on FontWeight that was bound to the Model property of TreeViewEntry).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload