How to set the value of a Gtk.ComboBox?

前端 未结 3 1183
醉话见心
醉话见心 2021-01-14 07:31

All I can figure out is something to do with the ComboBox.GetEnumerator or something like that.

I would like to do something like:

System.Collections         


        
3条回答
  •  不思量自难忘°
    2021-01-14 08:13

    The reason your code doesn't work is that the "items in the combobox" are actually the cell renderers packed into it for displaying columns of data. To get at the actual data, you need the TreeModel object.

    If you really must select based only on what's in the combo, here's how you can do it:

    string[] values = new string[]{"one", "two", "three"};
    var combo = new ComboBox(values);
    
    Gtk.TreeIter iter;
    combo.Model.GetIterFirst (out iter);
    do {
      GLib.Value thisRow = new GLib.Value ();
      combo.Model.GetValue (iter, 0, ref thisRow);
      if ((thisRow.Val as string).Equals("two")) {
        combo.SetActiveIter (iter);
        break;
      }
    } while (combo.Model.IterNext (ref iter));
    

    However, generally it's more succinct to keep your values indexed, like this:

    List values = new List(){"one", "two", "three"};  
    var combo = new ComboBox(values.ToArray());
    
    // Select "two"
    int row = values.IndexOf("two");
    Gtk.TreeIter iter;
    combo.Model.IterNthChild (out iter, row);
    combo.SetActiveIter (iter);
    

提交回复
热议问题