How to control the color of the text in a TreeView, if it is possible? #3588
-
Hi all, This is an amazing project! I'd like to build a TreeView and changing the text color depending on a property of the node. I could achieve defining the foreground and background color of field, but I am curious if the text color can be changed. I assume it is not as the content of the node "field" is text ( |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The Note that you return a ColorScheme not an Attribute or a Color
For the example I have used delegate for tree building, you can read more about that approach in Tree View Deep Dive. It is not a requirement though,
This is indeed the default implementation, however you can tailor the text that appears by using
using Terminal.Gui;
using Terminal.Gui.Trees;
namespace Test
{
public class Program
{
static void Main()
{
Application.Init();
var w = new Window() { Title = "My Window" };
var treeBuilder = new DelegateTreeBuilder<FileSystemInfo>(
(fsi) => {
try
{
return fsi is DirectoryInfo d ? d.GetFileSystemInfos() : Enumerable.Empty<FileSystemInfo>();
}
catch {
// Exception e.g. caused by file access permissions
return Enumerable.Empty<FileSystemInfo>();
}
}
);
var tv = new TreeView<FileSystemInfo>(treeBuilder)
{
Width = Dim.Fill(),
Height = Dim.Fill(),
};
tv.AddObjects(DriveInfo.GetDrives().Select(d=>d.RootDirectory));
tv.AspectGetter = (fsi) => fsi.Name;
var green = CreateScheme(Color.BrightGreen);
var white = CreateScheme(Color.White);
var red = CreateScheme(Color.Red);
tv.ColorGetter = (fsi) =>
{
if(fsi is FileSystemInfo fi && fi.Extension == ".exe")
{
return red;
}
return fsi is DirectoryInfo ? green : white;
};
w.Add(tv);
Application.Run(w);
Application.Shutdown();
return;
}
private static ColorScheme CreateScheme(Color foreground)
{
return new ColorScheme
{
Normal = new Terminal.Gui.Attribute(foreground, Color.Blue),
// flip color for selected nodes
Focus = new Terminal.Gui.Attribute(Color.Blue, foreground),
HotNormal = new Terminal.Gui.Attribute(foreground, Color.Blue),
HotFocus = new Terminal.Gui.Attribute(Color.Blue, foreground),
Disabled = new Terminal.Gui.Attribute(foreground, Color.Blue),
};
}
}
} |
Beta Was this translation helpful? Give feedback.
The
ColorGetter
delegate allows you to provide a function that returns aColorScheme
for each node. Below is an example that renders directories in green, executables in red and everything else in white.Note that you return a ColorScheme not an Attribute or a Color
For the example I have used delegate for tree building, you can read more about that approach in Tree View Deep Dive. It is not a requirement though,
ColorGetter
delegate works just fine on regularTreeView
too.