Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

c# - How to avoid winforms treeview icon changes when item selected

I'm experimenting with a treeview in a little C#/Winforms application. I have programatically assigned an ImageList to the treeview, and all nodes show their icons just fine, but when I click a node, its icon changes (to the very first image in the ImageList). How can I get the icon to remain unchanged?

BTW: The "SelectedImageIndex" is set to "(none)", since I don't really know what to set it to, since the image-index is different for the nodes (i guess?).

UPDATE: Here is the code of the application (I'm using Visual Studio Express 2008):

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            treeView1.BeginUpdate();
            treeView1.Nodes.Clear();
            treeView1.Nodes.Add("root","Project", 0);  

            treeView1.Nodes[0].Nodes.Add("Foo", "Foo", 2);
            treeView1.Nodes[0].Nodes[0].Nodes.Add("Fizz", "Fizz", 3);
            treeView1.Nodes[0].Nodes[0].Nodes.Add("Buzz", "Buzz", 3);

            treeView1.Nodes[0].Nodes.Add("Bar", "Bar", 1);
            treeView1.Nodes[0].Nodes[1].Nodes.Add("Fizz", "Fizz", 2);
            treeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Buzz", "Buzz", 3);

            treeView1.EndUpdate();
            treeView1.ImageList = imageList1;
        }
    }
}
question from:https://stackoverflow.com/questions/3415354/how-to-avoid-winforms-treeview-icon-changes-when-item-selected

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply set the SelectedImageIndex for each node to the same value as ImageIndex. So, if you're creating your node programatically:

        TreeNode node = new TreeNode("My Node");
        node.ImageIndex = 1;
        node.SelectedImageIndex = 1;

Or you can specify the whole lot in the constructor:

        TreeNode node = new TreeNode("My Node" ,1, 1);

You can do the same thing using the design time editor if you're adding nodes at design time. You just need to set the SelectedImageIndex at the node level and not at the TreeView level.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...