wpf中的treeview如何增加2级节点?在C#中如何添加?
WPF中TreeView的items一般为TreeViewItem,同时TreeViewItem自身又可以包含新的TreeViewItem,从而形成一棵子树,你想要几级节点就有几级节点了。
C#如下:
TreeView treeView = new TreeView();
//第一级,在treeView上添加
TreeViewItem treeViewItem1 = new TreeViewItem();
treeViewItem1.Header = "第一级";
treeView.Items.Add(treeViewItem1);
//第二级,在treeViewItem1上添加
TreeViewItem treeViewItem2 = new TreeViewItem();
treeViewItem2.Header = "第二级";
treeViewItem1.Items.Add(treeViewItem2);
//第三级,在treeViewItem2上添加
TreeViewItem treeViewItem3 = new TreeViewItem();
treeViewItem3.Header = "第三级";
treeViewItem2.Items.Add(treeViewItem3);
结果图:
再请问下,我如何能给TreeViewItem的name属性赋值呢,一赋值就报错
2023-12-06 广告
任务:树节点的展开,包括全展开,点击节点的展开,某一层节点的展开。
出发:
1.建树:<Grid>
<TreeView Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" Name="treeView1" VerticalAlignment="Top" Width="120" />
</Grid>
2.为树写节点类(注意继承类):
public class PropertyNodeItem : TreeViewItem
{
public int Level { get; set; }
public PropertyNodeItem(string name, string DisplayName, int level)
{
this.Level = level;
this.Header = DisplayName;
this.Name = name;
// 在此点下面插入创建对象所需的代码。
}
}
3.为树增加节点:
public void BindTreeView()
{
PropertyNodeItem node1 = new PropertyNodeItem("1","中国",0);
PropertyNodeItem node2 = new PropertyNodeItem("2","北京市",1);
PropertyNodeItem node3 = new PropertyNodeItem("3","吉林省",1);
PropertyNodeItem node4 = new PropertyNodeItem("4","上海市",1);
node1.Items.Add(node2);
node1.Items.Add(node3);
node1.Items.Add(node4);
PropertyNodeItem node5 = new PropertyNodeItem("5","海淀区",2);
PropertyNodeItem node6 = new PropertyNodeItem("6","朝阳区",2);
PropertyNodeItem node7 = new PropertyNodeItem("7","大兴区",2);
node2.Items.Add(node5);
node2.Items.Add(node6);
node2.Items.Add(node7);
PropertyNodeItem node8 = new PropertyNodeItem("8","白山市",2);
PropertyNodeItem node9 = new PropertyNodeItem("9","长春市",2);
node3.Items.Add(node8);
node3.Items.Add(node9);
PropertyNodeItem node10 = new PropertyNodeItem("10","抚松县",3);
PropertyNodeItem node11 = new PropertyNodeItem("11","靖宇县",3);
node8.Items.Add(node10);
node8.Items.Add(node11);
treeView1.Items.Clear();
treeView1.Items.Add(node1);
}
按F5,发现树是出来了,但是未展开,这样的树肯定是影响效果的,那么怎么展开呢,树本身并没有提供展开方法,此时,就该IsExpanded出场了。比如你想要树节点的Level=0的节点展开,只要设node1.IsExpanded = true;那么再F5,就可见效果。举一反三,想让所有的展开,则设置每个父节点的IsExpanded = true即可,又方便,又好理解
我只是想知道怎么建子节点而已...不要复制粘贴嘛,你这篇我看过了
关键是您要取一反三,不能什都让给您写好,这样您学程序是学不好的