TreeViewTemplate.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. namespace crown_tests.GtkExt
  4. {
  5. public class TreeViewTemplate: ITemplate
  6. {
  7. private List<TreeViewRowTemplate> RowTemplates = new List<TreeViewRowTemplate>();
  8. private List<Tuple<String, Gtk.CellRenderer>> Columns = new List<Tuple<String, Gtk.CellRenderer>>();
  9. public TreeViewTemplate()
  10. {
  11. }
  12. public TreeViewTemplate AddColumn(String Title, Gtk.CellRenderer renderer)
  13. {
  14. Columns.Add(Tuple.Create(Title, renderer));
  15. return this;
  16. }
  17. public TreeViewTemplate AddRowTemplate(TreeViewRowTemplate rowTemplate)
  18. {
  19. RowTemplates.Add(rowTemplate);
  20. return this;
  21. }
  22. public void Apply(Gtk.Widget widget)
  23. {
  24. Gtk.TreeView treeView = widget as Gtk.TreeView;
  25. if (treeView == null) {
  26. Console.WriteLine("TreeViewTemplate.Apply: Invalid widget type for this template");
  27. return;
  28. }
  29. foreach (var col in Columns) {
  30. treeView.AppendColumn(col.Item1, col.Item2, ValuePropertyDataFunc);
  31. }
  32. }
  33. private static void ValuePropertyDataFunc(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter)
  34. {
  35. var treeView = (Gtk.TreeView)column.TreeView;
  36. var info = Templating.GetTemplate(treeView) as TreeViewTemplate;
  37. var textCell = (cell as Gtk.CellRendererText);
  38. textCell.Text = string.Empty;
  39. var value = model.GetValue(iter, 0);
  40. if (value == null)
  41. return;
  42. foreach (var rowTemplate in info.RowTemplates) {
  43. if (value.GetType() == rowTemplate.TargetType) {
  44. //Here we have a value, which is the source for Binding, and a BindingInfo that is given by rowTemplate.ColumnBindings[column.Title] .
  45. //The instance of the BindingInfo is shared among all values (rows), since it was defined once in the rowTemplate.
  46. BindingInfo bindingInfo = null;
  47. if (!rowTemplate.ColumnBindings.TryGetValue(column.Title, out bindingInfo))
  48. return;
  49. //The actual binding, on the other hand, is specific to the current (row,column) pair.
  50. Binding binding = BindingEngine.GetOrCreateBinding(treeView, value, new TreeViewIterBindingTarget(treeView, iter, column), bindingInfo);
  51. var propValue = binding.GetSourceValue();
  52. textCell.Text = propValue == null ? String.Empty : propValue.ToString();
  53. return;
  54. }
  55. }
  56. }
  57. }
  58. }