I have a TreeView control, which contains multiple elements, nodes. Is there a way to change the selected item's foreground color or background color (by default blue background with white foreground is applied to the selected element) based on some condition. In my case, I will retrieve an object and check its 'NeedSync' property. If it's value is true, I'd want the element to have, for example, a green background. If it's false, I'd like the background to be red.
I looked at other similar threads, but the requirement there are to change the color of the unselected elements using the treeview's _DrawItem method. In WPF this should be possible by changing the controls style and specifying triggers.
What about here, in windows forms?
EDIT: I only have to change the font color or the backcolor of the selected element, everything else should stay the same. Is there a way to get the default style source code for the selected node? Implementing the drawNode method removes the collapsable icon, margins, some other things.
As said in the comments, you will need to change the DrawMode property to OwnerDrawText and then have something like this in the DrawNode event:
private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
Brush foreColour;
Brush backColour;
if (e.Node.IsSelected)
{
if (e.Node.Text == "Node1")
{
// Special highlight colouring
foreColour = Brushes.Yellow;
backColour = Brushes.Red;
}
else
{
// Default highlight colouring
foreColour = SystemBrushes.HighlightText;
backColour = SystemBrushes.Highlight;
}
}
else {
if (e.Node.Text == "Node1")
{
// Special colouring
foreColour = Brushes.Red;
backColour = Brushes.Yellow;
}
else
{
// Default colouring
foreColour = SystemBrushes.WindowText;
backColour = SystemBrushes.Window;
}
}
e.Graphics.FillRectangle(backColour, e.Bounds);
e.Graphics.DrawString(e.Node.Text, treeView1.Font, foreColour, e.Bounds);
}
(I don't know what criteria you want to use, so I added e.Node.Text == "Node1" as an example.)
NB: You may want to add additional (but similar) logic to fade the colours if the treeview loses focus.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With