自定义树视图 [英] Customize treeview
本文介绍了自定义树视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法自定义一个 winform 树视图来获得类似的东西?
Is there a way to customize a winform treeview to get something like ?
目的是让父项具有一种颜色,并定义一个三角形而不是 +/- 图标来展开项.
The purpose is to have one color by parent item an define a triangle instead of +/- icons to develop item.
推荐答案
使用 TreeViewDrawMode.OwnerDrawText
这样缩进将被 TreeView
调整.除此之外,你应该实现完整的绘画.
Use TreeViewDrawMode.OwnerDrawText
so the indenting will be adjusted by the TreeView
. Apart from that, you should implement the full painting.
public sealed class AdvancedTreeView : TreeView
{
public AdvancedTreeView()
{
DrawMode = TreeViewDrawMode.OwnerDrawText;
ShowLines = false;
AlternateBackColor = BackColor;
}
public Color AlternateBackColor { get; set; }
protected override void OnDrawNode(DrawTreeNodeEventArgs e)
{
// background
Color backColor = (GetTopNodeIndex(e.Node) & 1) == 0 ? BackColor : AlternateBackColor;
using (Brush b = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(b, new Rectangle(0, e.Bounds.Top, ClientSize.Width, e.Bounds.Height));
}
// icon
if (e.Node.Nodes.Count > 0)
{
Image icon = GetIcon(e.Node.IsExpanded); // TODO: true=down;false:right
e.Graphics.DrawImage(icon, e.Bounds.Left - icon.Width - 3, e.Bounds.Top);
}
// text (due to OwnerDrawText mode, indenting of e.Bounds will be correct)
TextRenderer.DrawText(e.Graphics, e.Node.Text, Font, e.Bounds, ForeColor);
// indicate selection (if not by backColor):
if ((e.State & TreeNodeStates.Selected) != 0)
ControlPaint.DrawFocusRectangle(e.Graphics, e.Bounds);
}
private int GetTopNodeIndex(TreeNode node)
{
while (node.Parent != null)
node = node.Parent;
return Nodes.IndexOf(node);
}
}
要获得与屏幕截图类似的结果,只需设置颜色即可.
To get the result similar to your screenshot just set the colors and you are done.
advancedTreeView1.BackColor = Color.DeepSkyBlue;
advancedTreeView1.AlternateBackColor = Color.LightBlue;
这篇关于自定义树视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文