先看效果,鼠标悬浮效果不理想,显示效果比较差,被我PASS了
在窗体上拖出TreeView控件,如果需要图标显示还需要拖出ImageList用来存图标
图标资源的话可以自己在网上找,我用的是阿里图库:https://www.iconfont.cn/
将ImageList和TreeView绑定起来,并将根节点编辑好
点击TreeView属性=》事件 双击圆圈中的事件
private void sideMenu_DrawNode(object sender, DrawTreeNodeEventArgs e) { e.DrawDefault = false; Graphics g = e.Graphics; SolidBrush txtBrush = new SolidBrush(Color.FromArgb(30, 123, 182)); //被选中的字体颜色 SolidBrush bacBrush = new SolidBrush(Color.FromArgb(243, 243, 243)); //被选中的背景颜色 SolidBrush txtBrush1 = new SolidBrush(Color.FromArgb(46, 45, 43)); //未选中的字体颜色 SolidBrush bacBrush1 = new SolidBrush(Color.FromArgb(255, 255, 255)); //未选中的背景颜色 int picSize = 25; int picX = e.Bounds.X + 20; int picY = e.Bounds.Y + sideMenu.ItemHeight / 5; StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; if (e.Node.IsSelected) { //节点背景 g.FillRectangle(bacBrush, e.Bounds); //节点名称 g.DrawString(e.Node.Text, sideMenu.Font, txtBrush, e.Bounds, sf); //g.DrawLine(new Pen(txtBrush, 10), e.Bounds.X, e.Bounds.Y, e.Bounds.X, e.Bounds.Y + e.Bounds.Width); } else { g.FillRectangle(bacBrush1, e.Bounds); g.DrawString(e.Node.Text, sideMenu.Font, txtBrush1, e.Bounds, sf); } var pen = new Pen(Brushes.LightGray, 1); g.DrawRectangle(pen, e.Bounds); if (sideImageList.Images.Count > 0) { g.DrawImage(sideImageList.Images[e.Node.ImageIndex], picX, picY, picSize, picSize); } txtBrush.Dispose(); bacBrush.Dispose(); txtBrush1.Dispose(); bacBrush1.Dispose(); pen.Dispose(); sf.Dispose(); g.Dispose(); }
最后一点比较重要:将DrawMode修改为OwnerDrawAll
鼠标点击效果如下