title: WPF TreeView - How do I bind a Parent/Child class
body: <p>I have a table that I would like to bind to a TreeView.</p>
  
  <pre><code>NODE    NAME        PARENT
  ----    -----       -------
  1       Bill        NULL
  2       Jane        NULL
  3       John        1
  4       Mike        2
  5       Bob         4
  6       Jody        1
  7       Larry       5
  8       Heather     2
  9       Steve       8
  </code></pre>
  
  <p>Here is my class:</p>
  
  <pre><code>public class Node
  {
      public int ID { get; set; }
      public string Name { get; set; }
      public int? Parent { get; set; }
  
      public Node()
      {
      }
  
      public Node(int id, string name)
      {
          ID = id;
          Name = name;
          Parent = null;
      }
  
      public Node(int id, string name, int? parent)
      {
          ID = id;
          Name = name;
          Parent = parent;
      }
  
      public override string ToString()
      {
          return string.Format("[{0}] {1}", ID, Name);
      }
  
  }
  </code></pre>
  
  <p>So the final result would look something like this:</p>
  
  <pre><code>---[1] Bill
    |-----[3] John
    |-----[4] Jody
  
  ---[2] Jane
    |-----[4] Mike
    |    |------[5] Bob
    |          |------[7] Larry
    |-----[8] Heather
         |------[9] Steve
  </code></pre>
  
  <p>Currently I am building this with code behind. 
  First I find all of the items that do not have parents. Then add them to the TreeView from code:</p>
  
  <pre><code>    var TopNodes = Nodes.Where(n =&gt; n.Parent == null);
  
      foreach (Node n in TopNodes)
      {
          TreeViewItem newItem = new TreeViewItem();
          newItem.Tag = n.ID;
          newItem.Header = n.Name;
  
          newItem.Items.Add("..Loading..");
          tvTest.Items.Add(newItem);
      }
  </code></pre>
  
  <p>Then when the item is expanded I populate the parent, like this:</p>
  
  <pre><code>private void tvTest_Expanded(object sender, RoutedEventArgs e)
  {
                  item.Items.Clear();
  
          int parentID = (int)item.Tag;
  
          var children = Nodes.Where(x =&gt; x.Parent == parentID);
  
          foreach (Node n in children)
          {
              TreeViewItem newItem = new TreeViewItem();
              newItem.Tag = n.ID;
              newItem.Header = n.Name;
  
              newItem.Items.Add("..Loading..");
              item.Items.Add(newItem);
          }
  
  }
  </code></pre>
  
  <p>I feel I would have more flexibility, if I could bind this data directly. Especially once I start working on implementing CRUD functions on the data.  </p>
  
  <p>Thank you for any advice that you can give me.</p>