开发者

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.No开发者_JS百科des[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;
        }
    }
}


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.


Hi You can also use the below code:

TreeNode Node = eventArgs.Node;
Node.SelectedImageKey = Node.ImageKey;


what can be done here is, we can utilize TreeView's HitTest method which gives the node information at a given point. Then with that info we can reset the Image to previous. Setting SelectedImageIndex to ImageIndex .Like so

var selectedNodeInfo = treeView.HitTest(treeView.PointToClient(Cursor.Position));
selectedNodeInfo.Node.SelectedImageIndex = selectedNodeInfo.Node.ImageIndex;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜