如何在Silverlight中的Treeview中添加子节点

时间:2012-11-02 09:34:46

标签: c# silverlight-4.0 treeview treeviewitem

我在Silverlight Page中有一个Treeview。现在我必须在Treeview中以编程方式将节点添加到每个节点的子节点。我可以这样做吗?

我的代码就像这样

 TreeViewItem item1 = new TreeViewItem();
 item1.Header = "Products";
 item1.Items.Add(new TreeViewItem() { Header = "Media Players" });
 item1.Items.Add(new TreeViewItem() { Header = "Games" });
 item1.Items.Add(new TreeViewItem() { Header = "Charts" });
 MyTreeView1.Items.Add(item1);

现在这将给我这样的输出

Products
   Media Players    
   Games
   Charts

但我想要这样的输出

Products
   Media Players 
      Games
         Charts

意味着必须将节点添加到新创建的节点的子节点。

1 个答案:

答案 0 :(得分:1)

这个怎么样?

    var products = new TreeViewItem {Header = "Products"};
    var mediaPlayers = new TreeViewItem() {Header = "Media Players"};
    var charts = new TreeViewItem() { Header = "Charts" };
    var games = new TreeViewItem() { Header = "Games" };

    products.Items.Add(mediaPlayers);
    mediaPlayers.Items.Add(games);
    games.Items.Add(charts);

MyTreeView1.Items.Add(products);