关于Gtk#和treeview:如何获得"选中"项目?
在Gtk#中,可以使用TreeView控件来实现树形视图,并且可以使用TreeSelection类来获取选中的项目。
以下是一个简单的示例代码:
using Gtk;
using System;
public class TreeViewExample : Window
{
public TreeViewExample() : base("TreeView Example")
{
SetDefaultSize(400, 200);
VBox box = new VBox(false, 2);
Add(box);
TreeView treeView = new TreeView(new TreeStore(typeof(string)));
box.PackStart(treeView, true, true, 0);
TreeViewColumn column = new TreeViewColumn("Items");
treeView.AppendColumn(column);
CellRendererText textRenderer = new CellRendererText();
column.PackStart(textRenderer, true);
column.AddAttribute(textRenderer, "text", 0);
TreeStore store = (TreeStore)treeView.Model;
store.AppendValues("Item 1");
store.AppendValues("Item 2");
store.AppendValues("Item 3");
treeView.Selection.Changed += Selection_Changed;
}
private void Selection_Changed(object sender, EventArgs e)
{
TreeView treeView = (TreeView)sender;
TreeSelection selection = treeView.Selection;
TreeIter iter;
if (selection.GetSelected(out iter))
{
TreeModel model = treeView.Model;
string item = (string)model.GetValue(iter, 0);
Console.WriteLine("Selected item: " + item);
}
}
protected override void OnDeleteEvent(EventArgs e)
{
Application.Quit();
base.OnDeleteEvent(e);
}
public static int Main(string[] args)
{
Application.Init();
TreeViewExample window = new TreeViewExample();
window.ShowAll();
Application.Run();
return 0;
}
}
在这个示例中,我们创建了一个TreeView控件,并且添加了一些项目。然后,我们使用TreeSelection类来获取选中的项目,并且在控制台中输出选中的项目。
希望这个答案能够帮助到你!
领取专属 10元无门槛券
手把手带您无忧上云