[v1] Best solution to enable (un)check item on TreeView with mouse ? #3896
-
I've a TreeView where I've added a "[v] " before the node text, to act as a checkbox (hooking the KeyDown event). Any suggestion ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
With TreeView alone it is difficult to achieve this as the 'hit test' methods etc are all internal. However in v2 you can combine table and tree views together using See the TableEditor scenario Terminal.Gui/UICatalog/Scenarios/TableEditor.cs Lines 973 to 985 in 81ad695 |
Beta Was this translation helpful? Give feedback.
-
If you are stuck using v1 then you can use reflection, here is an example for how to detect click in the first Rune after the branch lines of tree: using System.Reflection;
using Terminal.Gui;
using Terminal.Gui.Trees;
Application.Init();
Application.Run(new MyViewYay());
Application.Shutdown();
class MyViewYay : Window
{
private readonly TreeView _tv;
public MyViewYay()
{
_tv = new TreeView()
{
Width = Dim.Fill(),
Height = Dim.Fill()
};
_tv.AddObject(new TreeNode("Hello"));
_tv.MouseClick += Tv_MouseClick;
Add(_tv);
}
private void Tv_MouseClick(MouseEventArgs obj)
{
var ht = GetMethod(_tv.GetType(),"HitTest");
var branch = ht.Invoke(_tv, [obj.MouseEvent.Y]);
if (branch == null)
{
// No hit
return;
}
var getPrefix = GetMethod(branch.GetType(), "GetLinePrefix");
var prefix = (IEnumerable<Rune>)getPrefix.Invoke(branch, [Application.Driver]);
var hit = obj.MouseEvent.X == prefix.Count() + 1;
if (hit)
{
MessageBox.Query("Hit", $"Hit the first character of branch '{_tv.GetObjectOnRow(obj.MouseEvent.Y)}'", "Ok");
// If you want to avoid object selection change when toggling
obj.Handled=true;
}
}
MethodInfo GetMethod(Type type, string name)
{
var methods = new List<MethodInfo>();
while (type != null)
{
// Retrieve all methods declared on the current type
var typeMethods = type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly);
methods.AddRange(typeMethods);
// Move to the base type
type = type.BaseType;
}
return methods.SingleOrDefault(m => m.Name.Equals(name))
?? throw new InvalidOperationException($"Expected method '{name}' not found");
}
} |
Beta Was this translation helpful? Give feedback.
If you are stuck using v1 then you can use reflection, here is an example for how to detect click in the first Rune after the branch lines of tree: