http://blog.163.com/qiulei_21/blog/static/35071722201122452818390/
在网上找了很多资料,但是都是云山雾绕的,看了很久看不懂,今天终于在我同事的帮助下搞定了,要充分利用TreeViewItem的IsExpanded属性啊。
任务:树节点的展开,包括全展开,点击节点的展开,某一层节点的展开。
出发:
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即可,又方便,又好理解。