Nguyen Thien

Nguyen Thien

  • NA
  • 3
  • 900

How to insert root node in Treeview using EF

May 22 2015 9:29 PM
Hello, I want using EF to binding data in Treeview, but i don't insert root "All Family". I want insert it. Here are the instructions I follow:
 
XAML:
<Window x:Class="WpfTutorialSamples.TreeView_control.TreeViewMultipleTemplatesSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:self="clr-namespace:WpfTutorialSamples.TreeView_control"
Title="TreeViewMultipleTemplatesSample" Height="200" Width="250">
<Grid Margin="10">
<TreeView Name="trvFamilies">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type self:Family}" ItemsSource="{Binding Members}">
<StackPanel Orientation="Horizontal">
<Image Source="/WpfTutorialSamples;component/Images/group.png" Margin="0,0,5,0" />
<TextBlock Text="{Binding Name}" />
<TextBlock Text=" [" Foreground="Blue" />
<TextBlock Text="{Binding Members.Count}" Foreground="Blue" />
<TextBlock Text="]" Foreground="Blue" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type self:FamilyMember}">
<StackPanel Orientation="Horizontal">
<Image Source="/WpfTutorialSamples;component/Images/user.png" Margin="0,0,5,0" />
<TextBlock Text="{Binding Name}" />
<TextBlock Text=" (" Foreground="Green" />
<TextBlock Text="{Binding Age}" Foreground="Green" />
<TextBlock Text=" years)" Foreground="Green" />
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
</Window>
Code:
using System;
using System.Collections.Generic;
using System.Windows;
using System.Collections.ObjectModel;

namespace WpfTutorialSamples.TreeView_control
{
public partial class TreeViewMultipleTemplatesSample : Window
{
public TreeViewMultipleTemplatesSample()
{
InitializeComponent();

List<Family> families = new List<Family>();

Family family1 = new Family() { Name = "The Doe's" };
family1
.Members.Add(new FamilyMember() { Name = "John Doe", Age = 42 });
family1
.Members.Add(new FamilyMember() { Name = "Jane Doe", Age = 39 });
family1
.Members.Add(new FamilyMember() { Name = "Sammy Doe", Age = 13 });
families
.Add(family1);

Family family2 = new Family() { Name = "The Moe's" };
family2
.Members.Add(new FamilyMember() { Name = "Mark Moe", Age = 31 });
family2
.Members.Add(new FamilyMember() { Name = "Norma Moe", Age = 28 });
families
.Add(family2);

trvFamilies
.ItemsSource = families;
}
}

public class Family
{
public Family()
{
this.Members = new ObservableCollection<FamilyMember>();
}

public string Name { get; set; }

public ObservableCollection<FamilyMember> Members { get; set; }
}

public class FamilyMember
{
public string Name { get; set; }

public int Age { get; set; }
}
} 


Answers (1)