本C#教程将学习如何使用DevExpress TreeList控件加载数据(可动态)并绑定node点击事件,TreeList是devexpress中的一个树形结构列表,一般用于左侧菜单的加载,使用很普遍。那么该如何使用treeList控件呢?
1:我们只需要在界面中拖拽一个TreeList控件,就会在InitializeComponent控件初始化方法中生成一个treeList对象,如下:
private void InitializeComponent() { this.treeList1 = new DevExpress.XtraTreeList.TreeList(); }
2:然后在我们界面的Load方法初始化我们的treeList节点数据,因为小编界面对应的类为MainPanel.cs,所以新建这个界面的时候会自动生成一个类MainPanel_Load()相关的初始化方法,如下:
private void MainPanel_Load(object sender, EventArgs e) { //以下为TreeList控件样式相关设置 treeList1.BackColor = Color.Transparent; treeList1.Appearance.Empty.BackColor = Color.Transparent; treeList1.Appearance.Row.BackColor = Color.Transparent; treeList1.OptionsView.ShowColumns = false; //Node名称不可编辑 treeList1.OptionsBehavior.Editable = false; treeList1.OptionsView.ShowHorzLines = false; treeList1.OptionsView.ShowIndicator = false; treeList1.OptionsView.ShowVertLines = false; treeList1.OptionsSelection.InvertSelection = true; treeList1.LookAndFeel.UseDefaultLookAndFeel = false; treeList1.LookAndFeel.UseWindowsXPTheme = true; //设置treeList元素为可见 treeList1.Columns.Clear(); TreeListColumn newColumn = treeList1.Columns.Add(); newColumn.Caption = "Tree Column"; newColumn.Visible = true; //为treeList增加节点数据 treeList1.Nodes.Clear(); TreeListNode rootNode = treeList1.Nodes.Add(new Object[]{ "Root Node" }); TreeListNode child1 = rootNode.Nodes.Add(new Object[] { "Child 1" }); child1.Nodes.Add(new Object[] { "GrandChild 1.1" }); child1.Nodes.Add(new Object[]{ "GrandChild 1.2" }); TreeListNode child2 = rootNode.Nodes.Add(new Object[] { "Child 2" }); child2.Nodes.Add(new Object[] { "GrandChild2.1" }); child2.Nodes.Add(new Object[] { "GrandChild2.2" }); child2.Nodes.Add(new Object[] { "GrandChild2.3" }); //为treeList绑定双击事件 treeList1.DoubleClick += new EventHandler(treeList_DoubleClick); treeList1.RefreshNode(rootNode); }
3:实现名为treeList_DoubleClick的点击事件,这是一个treeList双击事件,方法如下:
private void treeList_DoubleClick(object sender, EventArgs e) { TreeList tree = sender as TreeList; //双击treeList元素时弹出node名称 MessageBox.Show("=============="+ tree.FocusedNode.GetDisplayText(0)); }
如上DevExpress TreeList控件加载数据之后的效果如下:
当我们点击TreeList元素的时候,会弹出一个提示框,说明我们的TreeList点击事件是成功的,如下: