Winform TreeView自定義樣式側邊導航欄


先看效果,鼠標懸浮效果不理想,顯示效果比較差,被我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

鼠標點擊效果如下

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM