gpt4 book ai didi

c# - 用不同的颜色给 TreeView 的节点上色

转载 作者:行者123 更新时间:2023-11-30 14:08:25 42 4
gpt4 key购买 nike

我有一个带有一些节点的 treeview。在某些情况下,我想为每个节点及其子节点着色不同的颜色。我写了一个给节点及其子节点上色的函数。

谁能告诉我是否有可能我将 Color.Green 作为变量,这样我就不会为每种颜色编写整个函数?我的意思是作为函数中的输入参数。

函数如下:

public void ColorChild(TreeNode nodes, int indx)
{
foreach (TreeNode node_tmp in nodes.Nodes[indx].Nodes)
{
System.Drawing.Color = Green;
node_tmp.ForeColor = color;
foreach (TreeNode node_tmp2 in node_tmp.Nodes)
{
node_tmp2.ForeColor = Color.Green;
foreach (TreeNode node_tmp3 in node_tmp2.Nodes)
{
node_tmp3.ForeColor = Color.Green;
foreach (TreeNode node_tmp4 in node_tmp3.Nodes)
{
node_tmp4.ForeColor = Color.Green;
foreach (TreeNode node_tmp5 in node_tmp4.Nodes)
{
node_tmp5.ForeColor = Color.Green;
}
}
}
}
}
}

最佳答案

如果树很大,您的解决方案会非常慢。只需在绘制节点时按需为节点着色即可。为此,您需要设置绘图模式:

treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText;

然后,当一个节点即将绘制时,按需询问它的颜色:

private void tree_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
TreeNodeStates state = e.State;
Font font = e.Node.NodeFont ?? e.Node.TreeView.Font;
Color foreColor;
Color backColor;

// node is selected
// if you want to see the color of a selected node, too,
// you can use inverted fore/back colors instead of system selection colors
if ((state & TreeNodeStates.Selected) == TreeNodeStates.Selected)
{
bool isFocused = (state & TreeNodeStates.Focused) == TreeNodeStates.Focused;
backColor = SystemColors.Highlight;
foreColor = isFocused ? SystemColors.HighlightText : SystemColors.InactiveCaptionText;
e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
if (isFocused)
ControlPaint.DrawFocusRectangle(e.Graphics, e.Bounds, foreColor, backColor);
TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, foreColor, TextFormatFlags.GlyphOverhangPadding | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPrefix);
}
// node is not selected
else
{
backColor = GetBackColor(e.Node); // GetBackColor: return some color by condition
foreColor = GetForeColor(e.Node); // GetForeColor: return some color by condition
using (Brush background = new SolidBrush(backColor))
{
e.Graphics.FillRectangle(background, e.Bounds);
TextRenderer.DrawText(e.Graphics, e.Node.Text, font, e.Bounds, foreColor, TextFormatFlags.GlyphOverhangPadding | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
}
}
}

如果条件改变了,就让树失效:

treeView1.Invalidate(); // this will re-draw the visible nodes

关于c# - 用不同的颜色给 TreeView 的节点上色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35155193/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com