【问题标题】:Gtk#: ListStore of object to ComboBoxEntryGtk#: 对象的 ListStore 到 ComboBoxEntry
【发布时间】:2015-01-17 15:40:03
【问题描述】:

我有一个包含一些字段(例如 field1、field2 等)的数据存储类,我想在 ComboBoxEntry 中显示此类的列表。我为 IEnumerable 创建扩展方法:

public static ListStore ToListStore<T>(this IEnumerable<T> Parent)
        {
            ListStore returnedValue = new ListStore(typeof (object));
            //ListStore returnedValue = new ListStore (typeof(string));

            if (Parent != null) 
            {
                foreach (T node in Parent) 
                {
                    returnedValue.AppendValues (node);
                    //next two lines is just for testing.
                    TreeIter hello;
                    bool res = returnedValue.GetIterFirst (out hello);
                }
            }

            return returnedValue;
        }

然后我用下一种方式填充 ComboBoxEntry:

public static void SetGenericModel<T>(this ComboBox Parent, IEnumerable<T> Model, CellLayoutDataFunc LayoutFuncForModel)
        {
            ListStore store = Model.ToListStore ();
            /*ListStore store = new ListStore (typeof(string));
            store.AppendValues("a");
            store.AppendValues("b");*/

            CellRendererText genericClassCell = new CellRendererText();
            //Parent.Clear ();
            Parent.PackStart(genericClassCell, true);
            Parent.SetCellDataFunc(genericClassCell, LayoutFuncForModel);
            TreeIter treeIter;
            store.GetIterFirst (out treeIter);
            Parent.Model = store;

            /*int columnsCount = Parent.Model.NColumns;

            Parent.Model.GetIterFirst (out treeIter);
            object obj = Parent.Model.GetValue (treeIter, columnsCount - 1);
            Parent.Clear ();*/
        }

好的,输出工作正常,但是当我尝试选择 ComboBoxEntry 的某些项目时,我的应用程序崩溃了,没有一些例外,只有输出窗口包含一些信息:*"(MyAppName:14822): GLib-GObject-WARNING ** :无法从“GtkSharpValue”类型的值设置“gchararray”类型的属性“文本”*。但是如果我将 ListStore 创建为字符串(注释代码):

ListStore store = new ListStore (typeof(string));
                store.AppendValues("a");
                store.AppendValues("b");

然后总是工作得很好。 我的代码有什么问题,如何解决这个问题(我应该用我的对象填充 ComboBoxEntry,因为当用户选择某个项目时,我应该将其作为数据存储区的项目处理)?

【问题讨论】:

    标签: c# combobox mono cross-platform gtk#


    【解决方案1】:

    我想 ComboboxEntry 默认情况下总是希望第一列是文本。也许这可以通过一些技巧来覆盖。但是文本条目期望值是文本而不是图标或其他任何东西似乎是合乎逻辑的......

    现在,我知道 Combobox(基类)默认将第一列作为文本。你注释掉的这行代码:

    Parent.Clear ();
    

    让您清除任何默认设置并打包您自己的渲染器。

    下一步是当您想读取 Combobox 的内容时,您必须使用 TreeIter 检索值,如下所示:

    TreeIter iter;
    
    if (Combo.GetActiveIter(out iter))
    {
        var value = (YourClass)this.Combo.Model.GetValue(iter, 0);
    } 
    

    【讨论】:

      猜你喜欢
      • 2020-07-19
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多