c#在TreeView中更改SelectNode的背景

时间:2016-10-27 22:14:22

标签: c# colors treeview nodes

我希望在TreeView控件中更改节点的背景颜色,以便在用户选择节点时,背景颜色从所选的选定节点更改为TreeView中的最顶层父节点。

这是我所追求的一个直观的例子:

TreeView node background example

1 个答案:

答案 0 :(得分:1)

根据您的图片,我假设您使用的是Windows窗体。因此,这是您需要的代码,您需要在此示例中使用名为treeview1的Treeview表单来实现所需的功能:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private readonly Color selectedColor = Color.Red;
    private readonly Color normalColor = Color.Transparent;

    private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
    {
        if (e.Action != TreeViewAction.ByKeyboard &&
            e.Action != TreeViewAction.ByMouse)
            return;

        ResetAllNodes(treeView1.Nodes.Cast<TreeNode>());
        ChangeBackground(e.Node);
    }

    private void ResetAllNodes(IEnumerable<TreeNode> nodes)
    {
        var treeNodes = nodes as TreeNode[] ?? nodes.ToArray();
        if (!treeNodes.Any())
            return;

        foreach (var node in treeNodes)
        {
            node.BackColor = normalColor;
            ResetAllNodes(node.Nodes.Cast<TreeNode>());
        }
    }

    private void ChangeBackground(TreeNode node)
    {
        node.BackColor = selectedColor;
        if (node.Parent == null)
            return;

        ChangeBackground(node.Parent);
    }
}

希望这有帮助!