简体   繁体   中英

Image index of TreeView node changes upon selection

When I tried using the imagelist in treeview, the image index changes when treenode is clicked. I have no idea why it is happening. Can anyone help me?

Thanks in advance

您需要在树节点上设置 ImageIndex 和 SelectedImageIndex。

'SelectedImageIndex's intent is to allow displaying a different image upon selection than what is set by the 'ImageIndex' for a particular node. To keep these two consistent it is necessary to set them to the same value. This can be done at design time or programmatically depending on your needs.

For example, if the images never change then it is as simple as setting them concurrently when a new node is added to the TreeView:

int myCurrentImageIndex = 0;
TreeNode node = myTreeView.Nodes.Add("new node!");
node.ImageIndex = node.SelectedImageIndex = myCurrentImageIndex;

However, if you do change the ImageIndex value for any reason after its initial creation (such as a response to some kind of user action), then you must also change the SelectedImageIndex as well. Otherwise, they will become inconsistent.

int myNewImageIndex = 1;
node.ImageIndex = node.SelectedImageIndex = myNewImageIndex;

(Note it is not enough to set them to be the same in the event handler of the 'AfterSelect' event. It must be done anywhere in your code where ImageIndex changes.)

您可以直接在构造函数中执行此操作:

TreeNode node = new TreeNode("My treenode", 1, 1);
TreeNode tn = new TreeNode();
tn.Text = "NewRecord";
tn.ImageIndex = 1;

treeView.SelectedNode.Nodes.Add(tn);
treeView.SelectedNode = tn;
treeView.SelectedNode.SelectedImageIndex = tn.ImageIndex; // <--- Problem solved
tn.BeginEdit();

只需添加这一行:

Node.SelectedIndex:=Node.ImageIndex;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM