网站首页 博客 C#重绘treeView行样式
绑定事件
this.treeView1.DrawMode = TreeViewDrawMode.OwnerDrawAll; this.treeView1.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNodeCustom);
重绘边框
/// <summary>
/// 调整TreeView 样式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <param name="imageList1">节点图片组件</param>
/// <param name="Width">总宽度</param>
/// <param name="ExpandImageIndex">展开图</param>
/// <param name="CollapseImageIndex">收缩图</param>
/// <param name="LeafImageIndex">叶子图</param>
public void SetTreeNodeDraw(object sender, DrawTreeNodeEventArgs e, ImageList imageList1, int Width, int ExpandImageIndex, int CollapseImageIndex, int LeafImageIndex)
{
TreeNode tn = e.Node as TreeNode;
if (tn == null)
{
return;
}
System.Drawing.Point ptbigimage = new System.Drawing.Point(tn.Bounds.X - 11, tn.Bounds.Y + 10);
System.Drawing.Point ptsmallimage = new System.Drawing.Point(tn.Bounds.X - 11, tn.Bounds.Y + 10);
Size szbig = new Size(11, 11);//打开收缩图片
Size szsmall = new Size(11, 11);//叶子图片
//Rectangle bcimage = new Rectangle(ptimage, new Size(33, 23));
//根据节点增加图片
if (tn.IsExpanded)
{
e.Graphics.DrawImage(imageList1.Images[ExpandImageIndex], new Rectangle(ptbigimage, szbig));
}
else if (tn.Nodes.Count > 0)
{
e.Graphics.DrawImage(imageList1.Images[CollapseImageIndex], new Rectangle(ptbigimage, szbig));
}
else
{
e.Graphics.DrawImage(imageList1.Images[LeafImageIndex], new Rectangle(ptsmallimage, szsmall));
}
//增加背景颜色
System.Drawing.Point pt = new System.Drawing.Point(tn.Bounds.X + 11, tn.Bounds.Y);
Brush bccolor = new SolidBrush(System.Drawing.Color.FromArgb(51, 153, 255));
Brush ybccolor = new SolidBrush(System.Drawing.Color.FromArgb(255, 255, 255));
Rectangle bcrt = new Rectangle(pt, new Size(Width - e.Bounds.X, e.Bounds.Height));//使用Width充满整行
if ((e.State & TreeNodeStates.Focused) != 0)
{
e.Graphics.FillRectangle(bccolor, bcrt);
}
else
{
e.Graphics.FillRectangle(ybccolor, bcrt);
}
//增加格线
using (Pen focusPen = new Pen(System.Drawing.Color.FromArgb(192, 192, 192)))
{
focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid;
e.Graphics.DrawRectangle(focusPen, bcrt);
}
//设置文本颜色和字体
System.Drawing.Point ptft = new System.Drawing.Point(tn.Bounds.X + 16, tn.Bounds.Y + 7);
System.Drawing.Rectangle rt = new System.Drawing.Rectangle(ptft, new Size(e.Bounds.Width, e.Bounds.Height));
System.Drawing.Brush bfcolor = new SolidBrush(System.Drawing.Color.FromArgb(59, 59, 59));
System.Drawing.Font nf = tn.NodeFont == null ? ((TreeView)sender).Font : tn.NodeFont;
e.Graphics.DrawString(e.Node.Text, nf, bfcolor, System.Drawing.Rectangle.Inflate(rt, 1, 4));
}