从代码中选择 GTK Treeview 项

Selecting GTK Treeview item from Code

在我向 GTK 树视图添加一些项目后,我需要 select 代码中列表中的第一项以触发 treeviewcursorchanged 事件 ie:when 单击树视图 item.I 需要 select 第一个 treeview item.But 没有 select 事件。 我用字符串

填充树视图
    liststore = new ListStore (typeof(string));
    treeview1.Model = liststore;  

select 离子在 GtkTreeView 中的逻辑被分成它自己的 class、GtkTreeSelection。每个 GtkTreeView 都有自己的 GtkTreeSelection,可通过 gtk_tree_view_get_selection().

获得

获得 GtkTreeSelection 后,您需要做的就是在您想要 select 的行中获取 GtkTreeIter 并调用 gtk_tree_selection_select_iter()。您还可以使用 gtk_tree_selection_select_path().

构建 GtkTreePath 和 select

如何获得 GtkTreeIterGtkTreePath 由您决定。 These are the methods that apply to GtkTreePaths and GtkTreeModels. A GtkListStore is also a GtkTreeModel, and has its own methods.

您必须使用与 Gtk.TreeView 关联的 Gtk.TreeSelection。对select第一行做如下操作:

Gtk.TreeIter iter;
if (liststore.GetIterFirst(out iter))
    treeview1.Selection.SelectIter(iter);

这是一个完整的示例,它创建了一个列表 view/model,向 selection changed 事件添加了一个信号处理程序,然后将第一行设置为 selected:

var view = new Gtk.TreeView();
var cell = new Gtk.CellRendererText();
var col1 = new Gtk.TreeViewColumn();
col1.Title = "Column 1"
col1.PackStart(cell, true);
col1.AddAttribute(cell, "text", 0);

view.AppendColumn(col1);

var model = new Gtk.ListStore(typeof(string));
model.AppendValues("AAA");
model.AppendValues("BBB");
model.AppendValues("CCC");

view.Model = model;

// This is the selection changed handler: I use a lambda but
// it is as easy to use a delegate `Changed` is a standard C#
// event.
view.Selection.Changed += (sender, e) => {
    Console.WriteLine("SELECTION WAS CHANGED");
    Gtk.TreeIter selected;
    if (view.Selection.GetSelected(out selected)) {
        Console.WriteLine("SELECTED ITEM: {0}", model.GetValue(selected, 0)));
    }
};

Gtk.TreeIter iter;
if (model.GetIterFirst(out iter))
     view.Selection.SelectIter(iter);