mazrabul
mazrabul

Reputation: 295

Switch positions of StateImage and IndexImage for a TreeNode in a Winforms TreeView control

I would like to know if it is possible to switch the position of a StateImage with that of an IndexImage for a TreeNode in a Winforms TreeView?

Please refer to the image below for an illustration.

A TreeNode with a StateImage and the bottom TreeNode without a StateImage

The first TreeNode has a stateImage and the second one doesn't.

My aim is for all IndexImages to align to the left and the StateImage (if any) to be to the right of the IndexImage.

The resulting tree would look something like:

resulting tree with IndexImages aligned left

I think i have to set the tree DrawMode to OwnerDraw and override OnPaint. I read this msdn link but nothing there was said about drawing images. I really don't know how to proceed. Any help and code you could provide (in C# or VB.net) will be very much appreciated.

Many thanks

Upvotes: 1

Views: 992

Answers (1)

LarsTech
LarsTech

Reputation: 81635

Yes, this would require custom drawing.

TreeView1.DrawMode = TreeViewDrawMode.OwnerDrawAll

Then you have to handle the DrawNode event. See TreeView.DrawNode Event

The DrawTreeNodeEventArgs parameter in the DrawNode event has a graphic object you can use to paint anything, from images to text.

Of course, once you go custom, you are responsible for drawing everything (unfortunately). See VisualStyles in regards to getting the proper TreeView glyphs.

Simple illustration:

Private Sub TreeView1_DrawNode(ByVal sender As Object, ByVal e As DrawTreeNodeEventArgs) Handles TreeView1.DrawNode
  Dim nodeLeft As Integer = (e.Node.Level * 16) + 16
  e.Graphics.DrawImage(ImageOne, nodeLeft, e.Bounds.Top)
  e.Graphics.DrawImage(ImageTwo, nodeLeft + 16, e.Bounds.Top)
  e.Graphics.DrawString(e.Node.Text, Me.Font, Brushes.Black, nodeLeft + 32, e.Bounds.Top)
End Sub

This example is missing code to draw the tree controls and the selection state, but it shows two images and the node text. Custom drawing TreeViews are a lot of work.

Upvotes: 1

Related Questions