Home > Software design >  How to only change TreeNode icon when expanded/collapsed and prevent changing Icon on selection?
How to only change TreeNode icon when expanded/collapsed and prevent changing Icon on selection?

Time:02-25

I have a TreeView where every node has a folder icon and I want that when those are expanded/collapsed that the folder icon changes. I don't want the icon to change when the node is only selected. So I have these event handlers for that

private void Tree_AfterExpand(object sender, TreeViewEventArgs e)
{
    e.Node.ImageIndex = 3;
}
private void Tree_AfterCollapse(object sender, TreeViewEventArgs e)
{
    e.Node.ImageIndex = 2;
}

// and this
TreeNode node = new TreeNode("My Node", 2, 2);

The problem is that when I select the item, since the default SelectedImageIndex in 0, it changed the folder icon to something else.

I have also tried just not setting a SelectedImageIndex but that defaults to 0 when the node is clicked. Is there any way to completely prevent all icon changes when selecting a node? Or what is the solution to this problem?

CodePudding user response:

Use the same index for both SelectedImageIndex and ImageIndex when initializing the nodes and also before collapse and expand:

node.ImageIndex = node.SelectedImageIndex = collapsedImageIndex;

For example:

int collapsedImageIndex = 0;
int expandedImageIndex = 1;
private void Form1_Load(object sender, EventArgs e)
{
    propertyGrid1.SelectedObject = new Class1();
    foreach (TreeNode node in treeView1.Nodes)
    {
        node.ImageIndex = node.SelectedImageIndex = collapsedImageIndex;
    }
}
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
    e.Node.ImageIndex = e.Node.SelectedImageIndex = expandedImageIndex;
}
private void treeView1_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
{
    e.Node.ImageIndex = e.Node.SelectedImageIndex = collapsedImageIndex;
}

CodePudding user response:

Selection has its' own index, so you just need to set it as well whenever you set a new image index:

    private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
    {
        e.Node.ImageIndex = 3;
        e.Node.SelectedImageIndex = 3;
    }

    private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e)
    {
        e.Node.ImageIndex = 2;
        e.Node.SelectedImageIndex = 2;
    }
  • Related