排序有点复杂,因为您需要让代码的多个部分(模型和列)协同工作。要对特定列进行排序,您需要执行以下操作:
- 创建一个列(无快捷方式)并为
SortColumnId 属性分配一个值。为简单起见,我通常分配列的序号 id,从 0 开始,即视图中的第一列为 0,第二列为 1,依此类推。
- 将您的模型包裹在
Gtk.TreeModelSort
- 在新模型上调用
SetSortFunc 一次,以获得您想要排序的列,并将您在 (1) 中设置的列 ID 作为第一个参数传递。确保匹配所有列 ID。
行的排序方式取决于您用作SetSortFunc 的第二个参数的委托。你得到模型和两个迭代器,你几乎可以做任何事情,甚至对多列进行排序(使用两个迭代器你可以从模型中获取任何值,而不仅仅是排序列中显示的值。)
这是一个简单的例子:
class MainClass
{
public static void Main (string[] args)
{
Application.Init ();
var win = CreateTreeWindow();
win.ShowAll ();
Application.Run ();
}
public static Gtk.Window CreateTreeWindow()
{
Gtk.Window window = new Gtk.Window("Sortable TreeView");
Gtk.TreeIter iter;
Gtk.TreeViewColumn col;
Gtk.CellRendererText cell;
Gtk.TreeView tree = new Gtk.TreeView();
cell = new Gtk.CellRendererText();
col = new Gtk.TreeViewColumn();
col.Title = "Column 1";
col.PackStart(cell, true);
col.AddAttribute(cell, "text", 0);
col.SortColumnId = 0;
tree.AppendColumn(col);
cell = new Gtk.CellRendererText();
col = new Gtk.TreeViewColumn();
col.Title = "Column 2";
col.PackStart(cell, true);
col.AddAttribute(cell, "text", 1);
tree.AppendColumn(col);
Gtk.TreeStore store = new Gtk.TreeStore(typeof (string), typeof (string));
iter = store.AppendValues("BBB");
store.AppendValues(iter, "AAA", "Zzz");
store.AppendValues(iter, "DDD", "Ttt");
store.AppendValues(iter, "CCC", "Ggg");
iter = store.AppendValues("AAA");
store.AppendValues(iter, "ZZZ", "Zzz");
store.AppendValues(iter, "GGG", "Ggg");
store.AppendValues(iter, "TTT", "Ttt");
Gtk.TreeModelSort sortable = new Gtk.TreeModelSort(store);
sortable.SetSortFunc(0, delegate(TreeModel model, TreeIter a, TreeIter b) {
string s1 = (string)model.GetValue(a, 0);
string s2 = (string)model.GetValue(b, 0);
return String.Compare(s1, s2);
});
tree.Model = sortable;
window.Add(tree);
return window;
}
}